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-new-snippet-default "\
191 # -*- mode: snippet -*-
193 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
194 # binding: ${4:direct-keybinding}}${5:
195 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
199 "Default snippet to use when creating a new snippet. If nil,
200 don't use any snippet."
204 (defcustom yas-prompt-functions '(yas-x-prompt
206 yas-completing-prompt
209 "Functions to prompt for keys, templates, etc interactively.
211 These functions are called with the following arguments:
213 - PROMPT: A string to prompt the user
215 - CHOICES: a list of strings or objects.
217 - optional DISPLAY-FN : A function that, when applied to each of
218 the objects in CHOICES will return a string.
220 The return value of any function you put here should be one of
221 the objects in CHOICES, properly formatted with DISPLAY-FN (if
224 - To signal that your particular style of prompting is
225 unavailable at the moment, you can also have the function return
228 - To signal that the user quit the prompting process, you can
231 (signal 'quit \"user quit!\")."
232 :type '(repeat function)
235 (defcustom yas-indent-line 'auto
236 "Controls indenting applied to a recent snippet expansion.
238 The following values are possible:
240 - `fixed' Indent the snippet to the current column;
242 - `auto' Indent each line of the snippet with `indent-according-to-mode'
244 Every other value means don't apply any snippet-side indentation
245 after expansion (the manual per-line \"$>\" indentation still
247 :type '(choice (const :tag "Nothing" nothing)
248 (const :tag "Fixed" fixed)
249 (const :tag "Auto" auto))
252 (defcustom yas-also-auto-indent-first-line nil
253 "Non-nil means also auto indent first line according to mode.
255 Naturally this is only valid when `yas-indent-line' is `auto'"
259 (defcustom yas-snippet-revival t
260 "Non-nil means re-activate snippet fields after undo/redo."
264 (defcustom yas-triggers-in-field nil
265 "If non-nil, allow stacked expansions (snippets inside snippets).
267 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
272 (defcustom yas-fallback-behavior 'call-other-command
273 "How to act when `yas-expand' does *not* expand a snippet.
275 - `call-other-command' means try to temporarily disable YASnippet
276 and call the next command bound to whatever key was used to
279 - nil or the symbol `return-nil' mean do nothing. (and
280 `yas-expand' returns nil)
282 - A Lisp form (apply COMMAND . ARGS) means interactively call
283 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
284 with ARGS as arguments."
285 :type '(choice (const :tag "Call previous command" call-other-command)
286 (const :tag "Do nothing" return-nil))
289 (defcustom yas-choose-keys-first nil
290 "If non-nil, prompt for snippet key first, then for template.
292 Otherwise prompts for all possible snippet names.
294 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
298 (defcustom yas-choose-tables-first nil
299 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
301 Otherwise, user chooses between the merging together of all
304 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
308 (defcustom yas-use-menu 'abbreviate
309 "Display a YASnippet menu in the menu bar.
311 When non-nil, submenus for each snippet table will be listed
312 under the menu \"Yasnippet\".
314 - If set to `abbreviate', only the current major-mode
315 menu and the modes set in `yas-extra-modes' are listed.
317 - If set to `full', every submenu is listed
319 - It set to nil, don't display a menu at all (this requires a
320 `yas-reload-all' call if the menu is already visible).
322 Any other non-nil value, every submenu is listed."
323 :type '(choice (const :tag "Full" full)
324 (const :tag "Abbreviate" abbreviate)
325 (const :tag "No menu" nil))
328 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
330 (char-to-string ?\x21E5))) ;; little ->| sign
332 "The text that will be used in menu to represent the trigger."
336 (defcustom yas-wrap-around-region nil
337 "If non-nil, snippet expansion wraps around selected region.
339 The wrapping occurs just before the snippet's exit marker. This
340 can be overridden on a per-snippet basis."
344 (defcustom yas-good-grace t
345 "If non-nil, don't raise errors in inline elisp evaluation.
347 An error string \"[yas] error\" is returned instead."
351 (defcustom yas-visit-from-menu nil
352 "If non-nil visit snippets's files from menu, instead of expanding them.
354 This can only work when snippets are loaded from files."
358 (defcustom yas-expand-only-for-last-commands nil
359 "List of `last-command' values to restrict tab-triggering to, or nil.
361 Leave this set at nil (the default) to be able to trigger an
362 expansion simply by placing the cursor after a valid tab trigger,
363 using whichever commands.
365 Optionally, set this to something like '(self-insert-command) if
366 you to wish restrict expansion to only happen when the last
367 letter of the snippet tab trigger was typed immediately before
368 the trigger key itself."
369 :type '(repeat function)
372 ;; Only two faces, and one of them shouldn't even be used...
374 (defface yas-field-highlight-face
375 '((t (:inherit 'region)))
376 "The face used to highlight the currently active field of a snippet"
379 (defface yas--field-debug-face
381 "The face used for debugging some overlays normally hidden"
385 ;;; User-visible variables
387 (defvar yas-keymap (let ((map (make-sparse-keymap)))
388 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
389 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
390 (define-key map [(shift tab)] 'yas-prev-field)
391 (define-key map [backtab] 'yas-prev-field)
392 (define-key map (kbd "C-g") 'yas-abort-snippet)
393 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
395 "The active keymap while a snippet expansion is in progress.")
397 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
398 "List of character syntaxes used to find a trigger key before point.
399 The list is tried in the order while scanning characters
400 backwards from point. For example, if the list is '(\"w\" \"w_\")
401 first look for trigger keys which are composed exclusively of
402 \"word\"-syntax characters, and then, if that fails, look for
403 keys which are either of \"word\" or \"symbol\"
404 syntax. Triggering after
408 will, according to the \"w\" element first try \"bar\". If that
409 isn't a trigger key, \"foo-bar\" is tried, respecting a second
412 (defvar yas-after-exit-snippet-hook
414 "Hooks to run after a snippet exited.
416 The hooks will be run in an environment where some variables bound to
419 `yas-snippet-beg' : The beginning of the region of the snippet.
421 `yas-snippet-end' : Similar to beg.
423 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
425 (defvar yas-before-expand-snippet-hook
427 "Hooks to run just before expanding a snippet.")
429 (defvar yas-buffer-local-condition
430 '(if (and (or (fourth (syntax-ppss))
431 (fifth (syntax-ppss)))
433 (eq this-command 'yas-expand-from-trigger-key))
434 '(require-snippet-condition . force-in-comment)
436 "Snippet expanding condition.
438 This variable is a Lisp form which is evaluated every time a
439 snippet expansion is attempted:
441 * If it evaluates to nil, no snippets can be expanded.
443 * If it evaluates to the a cons (require-snippet-condition
446 * Snippets bearing no \"# condition:\" directive are not
449 * Snippets bearing conditions that evaluate to nil (or
450 produce an error) won't be considered.
452 * If the snippet has a condition that evaluates to non-nil
455 * If REQUIREMENT is t, the snippet is considered
457 * If REQUIREMENT is `eq' RESULT, the snippet is
460 * Otherwise, the snippet is not considered.
462 * If it evaluates to the symbol 'always, all snippets are
463 considered for expansion, regardless of any conditions.
465 * If it evaluates to t or some other non-nil value
467 * Snippet bearing no conditions, or conditions that
468 evaluate to non-nil, are considered for expansion.
470 * Otherwise, the snippet is not considered.
472 Here's an example preventing snippets from being expanded from
473 inside comments, in `python-mode' only, with the exception of
474 snippets returning the symbol 'force-in-comment in their
477 (add-hook 'python-mode-hook
479 (setq yas-buffer-local-condition
480 '(if (python-in-string/comment)
481 '(require-snippet-condition . force-in-comment)
484 The default value is similar, it filters out potential snippet
485 expansions inside comments and string literals, unless the
486 snippet itself contains a condition that returns the symbol
487 `force-in-comment'.")
490 ;;; Internal variables
492 (defvar yas--version "0.8.0beta")
494 (defvar yas--menu-table (make-hash-table)
495 "A hash table of MAJOR-MODE symbols to menu keymaps.")
497 (defvar yas--known-modes
498 '(ruby-mode rst-mode markdown-mode)
499 "A list of mode which is well known but not part of Emacs.")
501 (defvar yas--escaped-characters
502 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
503 "List of characters which *might* need to be escaped.")
505 (defconst yas--field-regexp
506 "${\\([0-9]+:\\)?\\([^}]*\\)}"
507 "A regexp to *almost* recognize a field.")
509 (defconst yas--multi-dollar-lisp-expression-regexp
510 "$+[ \t\n]*\\(([^)]*)\\)"
511 "A regexp to *almost* recognize a \"$(...)\" expression.")
513 (defconst yas--backquote-lisp-expression-regexp
515 "A regexp to recognize a \"`lisp-expression`\" expression." )
517 (defconst yas--transform-mirror-regexp
518 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
519 "A regexp to *almost* recognize a mirror with a transform.")
521 (defconst yas--simple-mirror-regexp
523 "A regexp to recognize a simple mirror.")
525 (defvar yas--snippet-id-seed 0
526 "Contains the next id for a snippet.")
528 (defun yas--snippet-next-id ()
529 (let ((id yas--snippet-id-seed))
530 (incf yas--snippet-id-seed)
536 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
537 (defvar last-buffer-undo-list nil)
539 (defvar yas--minor-mode-menu nil
540 "Holds the YASnippet menu.")
542 (defun yas--init-minor-keymap ()
543 "Set up the `yas-minor-mode' keymap."
544 (let ((map (make-sparse-keymap)))
546 (easy-menu-define yas--minor-mode-menu
548 "Menu used when `yas-minor-mode' is active."
551 ["Expand trigger" yas-expand
552 :help "Possibly expand tab trigger before point"]
553 ["Insert at point..." yas-insert-snippet
554 :help "Prompt for an expandable snippet and expand it at point"]
555 ["New snippet..." yas-new-snippet
556 :help "Create a new snippet in an appropriate directory"]
557 ["Visit snippet file..." yas-visit-snippet-file
558 :help "Prompt for an expandable snippet and find its file"]
560 ("Snippet menu behaviour"
561 ["Visit snippets" (setq yas-visit-from-menu t)
562 :help "Visit snippets from the menu"
563 :active t :style radio :selected yas-visit-from-menu]
564 ["Expand snippets" (setq yas-visit-from-menu nil)
565 :help "Expand snippets from the menu"
566 :active t :style radio :selected (not yas-visit-from-menu)]
568 ["Show all known modes" (setq yas-use-menu 'full)
569 :help "Show one snippet submenu for each loaded table"
570 :active t :style radio :selected (eq yas-use-menu 'full)]
571 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
572 :help "Show only snippet submenus for the current active modes"
573 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
575 ["Auto" (setq yas-indent-line 'auto)
576 :help "Indent each line of the snippet with `indent-according-to-mode'"
577 :active t :style radio :selected (eq yas-indent-line 'auto)]
578 ["Fixed" (setq yas-indent-line 'fixed)
579 :help "Indent the snippet to the current column"
580 :active t :style radio :selected (eq yas-indent-line 'fixed)]
581 ["None" (setq yas-indent-line 'none)
582 :help "Don't apply any particular snippet indentation after expansion"
583 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
585 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
586 (not yas-also-auto-indent-first-line))
587 :help "When auto-indenting also, auto indent the first line menu"
588 :active (eq yas-indent-line 'auto)
589 :style toggle :selected yas-also-auto-indent-first-line]
592 ["System X-widget" (setq yas-prompt-functions
594 (remove 'yas-x-prompt
595 yas-prompt-functions)))
596 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
597 :active t :style radio :selected (eq (car yas-prompt-functions)
599 ["Dropdown-list" (setq yas-prompt-functions
600 (cons 'yas-dropdown-prompt
601 (remove 'yas-dropdown-prompt
602 yas-prompt-functions)))
603 :help "Use a special dropdown list"
604 :active t :style radio :selected (eq (car yas-prompt-functions)
605 'yas-dropdown-prompt)]
606 ["Ido" (setq yas-prompt-functions
607 (cons 'yas-ido-prompt
608 (remove 'yas-ido-prompt
609 yas-prompt-functions)))
610 :help "Use an ido-style minibuffer prompt"
611 :active t :style radio :selected (eq (car yas-prompt-functions)
613 ["Completing read" (setq yas-prompt-functions
614 (cons 'yas-completing-prompt
615 (remove 'yas-completing-prompt
616 yas-prompt-functions)))
617 :help "Use a normal minibuffer prompt"
618 :active t :style radio :selected (eq (car yas-prompt-functions)
619 'yas-completing-prompt)]
622 ["Wrap region in exit marker"
623 (setq yas-wrap-around-region
624 (not yas-wrap-around-region))
625 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
626 :style toggle :selected yas-wrap-around-region]
627 ["Allow stacked expansions "
628 (setq yas-triggers-in-field
629 (not yas-triggers-in-field))
630 :help "If non-nil allow snippets to be triggered inside other snippet fields"
631 :style toggle :selected yas-triggers-in-field]
632 ["Revive snippets on undo "
633 (setq yas-snippet-revival
634 (not yas-snippet-revival))
635 :help "If non-nil allow snippets to become active again after undo"
636 :style toggle :selected yas-snippet-revival]
639 (not yas-good-grace))
640 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
641 :style toggle :selected yas-good-grace]
644 ["Load snippets..." yas-load-directory
645 :help "Load snippets from a specific directory"]
646 ["Reload everything" yas-reload-all
647 :help "Cleanup stuff, reload snippets, rebuild menus"]
649 :help "Display some information about YASnippet"])))
651 ;; Now for the stuff that has direct keybindings
653 (define-key map [(tab)] 'yas-expand)
654 (define-key map (kbd "TAB") 'yas-expand)
655 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
656 (define-key map "\C-c&\C-n" 'yas-new-snippet)
657 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
660 (defvar yas-minor-mode-map (yas--init-minor-keymap)
661 "The keymap used when `yas-minor-mode' is active.")
663 (defvar yas--tables (make-hash-table)
664 "A hash table of mode symbols to `yas--table' objects.")
666 (defvar yas--parents (make-hash-table)
667 "A hash table of mode symbols do lists of direct parent mode symbols.
669 This list is populated when reading the \".yas-parents\" files
670 found when traversing snippet directories with
671 `yas-load-directory'.
673 There might be additional parenting information stored in the
674 `derived-mode-parent' property of some mode symbols, but that is
677 (defvar yas--ancestors (make-hash-table)
678 "A hash table of mode symbols do lists of all parent mode symbols.
680 A cache managed by `yas--all-parents'")
682 (defvar yas--direct-keymaps (list)
683 "Keymap alist supporting direct snippet keybindings.
685 This variable is placed in `emulation-mode-map-alists'.
687 Its elements looks like (TABLE-NAME . KEYMAP). They're
688 instantiated on `yas-reload-all' but KEYMAP is added to only when
689 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
690 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
691 defined direct keybindings to the command
692 `yas-expand-from-keymap' which then which snippet to expand.")
694 (defun yas-direct-keymaps-reload ()
695 "Force reload the direct keybinding for active snippet tables."
697 (setq yas--direct-keymaps nil)
698 (maphash #'(lambda (name table)
699 (push (cons (intern (format "yas--direct-%s" name))
700 (yas--table-direct-keymap table))
701 yas--direct-keymaps))
704 (defun yas--modes-to-activate ()
705 "Compute list of mode symbols that are active for `yas-expand'
707 (let ((modes-to-activate (list major-mode))
709 (while (setq mode (get mode 'derived-mode-parent))
710 (push mode modes-to-activate))
711 (dolist (mode (yas-extra-modes))
712 (push mode modes-to-activate))
714 (append modes-to-activate
715 (mapcan #'(lambda (mode)
716 (yas--all-parents mode))
717 modes-to-activate)))))
719 (defvar yas-minor-mode-hook nil
720 "Hook run when `yas-minor-mode' is turned on.")
723 (define-minor-mode yas-minor-mode
724 "Toggle YASnippet mode.
726 When YASnippet mode is enabled, `yas-expand', normally bound to
727 the TAB key, expands snippets of code depending on the major
730 With no argument, this command toggles the mode.
731 positive prefix argument turns on the mode.
732 Negative prefix argument turns off the mode.
735 \\{yas-minor-mode-map}"
737 ;; The indicator for the mode line.
740 (cond (yas-minor-mode
741 ;; Install the direct keymaps in `emulation-mode-map-alists'
742 ;; (we use `add-hook' even though it's not technically a hook,
743 ;; but it works). Then define variables named after modes to
744 ;; index `yas--direct-keymaps'.
746 ;; Also install the post-command-hook.
748 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
749 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
750 ;; Set the `yas--direct-%s' vars for direct keymap expansion
752 (dolist (mode (yas--modes-to-activate))
753 (let ((name (intern (format "yas--direct-%s" mode))))
754 (set-default name nil)
755 (set (make-local-variable name) t)))
758 (yas--load-pending-jits))
760 ;; Uninstall the direct keymaps and the post-command hook
762 (remove-hook 'post-command-hook 'yas--post-command-handler t)
763 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
765 (defvar yas-dont-activate '(minibufferp)
766 "If non-nil don't let `yas-global-mode' affect some buffers.
768 If a function of zero arguments, then its result is used.
770 If a list of functions, then all functions must return nil to
771 activate yas for this buffer.
773 In Emacsen <= 23, this variable is buffer-local. Because
774 `yas-minor-mode-on' is called by `yas-global-mode' after
775 executing the buffer's major mode hook, setting this variable
776 there is an effective way to define exceptions to the \"global\"
777 activation behaviour.
779 In Emacsen > 23, only the global value is used. To define
780 per-mode exceptions to the \"global\" activation behaviour, call
781 `yas-minor-mode' with a negative argument directily in the major
783 (unless (> emacs-major-version 23)
784 (make-variable-buffer-local 'yas-dont-activate))
787 (defun yas-minor-mode-on ()
788 "Turn on YASnippet minor mode.
790 Honour `yas-dont-activate', which see."
792 ;; Check `yas-dont-activate'
793 (unless (cond ((functionp yas-dont-activate)
794 (funcall yas-dont-activate))
795 ((consp yas-dont-activate)
796 (some #'funcall yas-dont-activate))
801 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
805 (defun yas--global-mode-reload-with-jit-maybe ()
806 "Run `yas-reload-all' when `yas-global-mode' is on."
807 (when yas-global-mode (yas-reload-all)))
809 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
814 (defvar yas--font-lock-keywords
815 (append '(("^#.*$" . font-lock-comment-face))
816 lisp-font-lock-keywords
817 lisp-font-lock-keywords-1
818 lisp-font-lock-keywords-2
820 (0 font-lock-keyword-face)
821 (1 font-lock-string-face t))
823 (0 font-lock-keyword-face)
824 (1 font-lock-warning-face t))
825 ("${" font-lock-keyword-face)
826 ("$[0-9]+?" font-lock-preprocessor-face)
827 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
829 (0 font-lock-keyword-face)))))
831 (defun yas--init-major-keymap ()
832 "Setup YASnippet major-mode keymap."
833 (let ((map (make-sparse-keymap)))
834 (easy-menu-define nil
836 "Menu used when snippet-mode is active."
838 (mapcar #'(lambda (ent)
840 (define-key map (third ent) (second ent)))
841 (vector (first ent) (second ent) t))
843 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
844 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
847 (defvar snippet-mode-map
848 (yas--init-major-keymap)
849 "The keymap used when `snippet-mode' is active.")
852 (define-derived-mode snippet-mode text-mode "Snippet"
853 "A mode for editing yasnippets"
854 (setq font-lock-defaults '(yas--font-lock-keywords))
855 (set (make-local-variable 'require-final-newline) nil)
856 (set (make-local-variable 'comment-start) "#")
857 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
861 ;;; Internal structs for template management
863 (defstruct (yas--template (:constructor yas--make-blank-template))
864 "A template for a snippet."
874 group ;; as dictated by the #group: directive or .yas-make-groups
875 perm-group ;; as dictated by `yas-define-menu'
879 (defun yas--populate-template (template &rest args)
880 "Helper function to populate TEMPLATE with properties."
884 (position (intern (substring (symbol-name (car args)) 1))
885 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
887 (setq args (cddr args)))
890 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
891 "A table to store snippets for a particular mode.
893 Has the following fields:
897 A symbol name normally corresponding to a major mode, but can
898 also be a pseudo major-mode to be referenced in
899 `yas-extra-modes', for example.
903 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
904 a string or a vector, where the former is the snippet's trigger
905 and the latter means it's a direct keybinding. NAMEHASH is yet
906 another hash of (NAME . TEMPLATE) where NAME is the snippet's
907 name and TEMPLATE is a `yas--template' object.
909 `yas--table-direct-keymap'
911 A keymap for the snippets in this table that have direct
912 keybindings. This is kept in sync with the keyhash, i.e., all
913 the elements of the keyhash that are vectors appear here as
914 bindings to `yas-expand-from-keymap'.
916 `yas--table-uuidhash'
918 A hash table mapping snippets uuid's to the same `yas--template'
919 objects. A snippet uuid defaults to the snippet's name.
922 (hash (make-hash-table :test 'equal))
923 (uuidhash (make-hash-table :test 'equal))
925 (direct-keymap (make-sparse-keymap)))
927 (defun yas--get-template-by-uuid (mode uuid)
928 "Find the snippet template in MODE by its UUID."
929 (let* ((table (gethash mode yas--tables mode)))
931 (gethash uuid (yas--table-uuidhash table)))))
933 ;; Apropos storing/updating in TABLE, this works in two steps:
935 ;; 1. `yas--remove-template-by-uuid' removes any
936 ;; keyhash-namehash-template mappings from TABLE, grabbing the
937 ;; snippet by its uuid. Also removes mappings from TABLE's
938 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
939 ;; of potentially stale menu bindings right?.)
941 ;; 2. `yas--add-template' adds this all over again.
943 ;; Create a new or add to an existing keyhash-namehash mapping.
945 ;; For reference on understanding this, consider three snippet
948 ;; A: # name: The Foo
950 ;; # binding: C-c M-l
952 ;; B: # name: Mrs Foo
955 ;; C: # name: The Bar
956 ;; # binding: C-c M-l
961 ;; keyhash namehashes(3) yas--template structs(4)
962 ;; -----------------------------------------------------
965 ;; "foo" ---> "The Foo" ---> [yas--template A] |
966 ;; "Mrs Foo" ---> [yas--template B] |
968 ;; [C-c M-l] ---> "The Foo" -------------------------/
969 ;; "The Bar" ---> [yas--template C]
971 ;; "baz" ---> "Baz" ---> [yas--template D]
973 ;; Additionally, since uuid defaults to the name, we have a
974 ;; `yas--table-uuidhash' for TABLE
976 ;; uuidhash yas--template structs
977 ;; -------------------------------
978 ;; "The Foo" ---> [yas--template A]
979 ;; "Mrs Foo" ---> [yas--template B]
980 ;; "The Bar" ---> [yas--template C]
981 ;; "Baz" ---> [yas--template D]
983 ;; FIXME: the more I look at this data-structure the more I think I'm
984 ;; stupid. There has to be an easier way (but beware lots of code
987 (defun yas--remove-template-by-uuid (table uuid)
988 "Remove from TABLE a template identified by UUID."
989 (let ((template (gethash uuid (yas--table-uuidhash table))))
991 (let* ((name (yas--template-name template))
993 ;; Remove the name from each of the targeted namehashes
995 (maphash #'(lambda (k v)
996 (let ((template (gethash name v)))
998 (eq uuid (yas--template-uuid template)))
1000 (when (zerop (hash-table-count v))
1001 (push k empty-keys)))))
1002 (yas--table-hash table))
1003 ;; Remove the namehash themselves if they've become empty
1005 (dolist (key empty-keys)
1007 (define-key (yas--table-direct-keymap table) key nil))
1008 (remhash key (yas--table-hash table)))
1010 ;; Finally, remove the uuid from the uuidhash
1012 (remhash uuid (yas--table-uuidhash table))))))
1014 (defun yas--add-template (table template)
1015 "Store in TABLE the snippet template TEMPLATE.
1017 KEY can be a string (trigger key) of a vector (direct
1019 (let ((name (yas--template-name template))
1020 (key (yas--template-key template))
1021 (keybinding (yas--template-keybinding template))
1022 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1023 (dolist (k (remove nil (list key keybinding)))
1027 (yas--table-hash table))
1029 (make-hash-table :test 'equal)
1030 (yas--table-hash table))))
1032 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1034 ;; Update TABLE's `yas--table-uuidhash'
1035 (puthash (yas--template-uuid template)
1037 (yas--table-uuidhash table))))
1039 (defun yas--update-template (table template)
1040 "Add or update TEMPLATE in TABLE.
1042 Also takes care of adding and updating to the associated menu."
1043 ;; Remove from table by uuid
1045 (yas--remove-template-by-uuid table (yas--template-uuid template))
1046 ;; Add to table again
1048 (yas--add-template table template)
1049 ;; Take care of the menu
1052 (yas--update-template-menu table template)))
1054 (defun yas--update-template-menu (table template)
1055 "Update every menu-related for TEMPLATE."
1056 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1057 (key (yas--template-key template))
1058 (keybinding (yas--template-keybinding template)))
1059 ;; The snippet might have changed name or keys, so update
1060 ;; user-visible strings
1062 (unless (eq (cdr menu-binding-pair) :none)
1063 ;; the menu item name
1065 (setf (cadar menu-binding-pair) (yas--template-name template))
1066 ;; the :keys information (also visible to the user)
1067 (setf (getf (cdr (car menu-binding-pair)) :keys)
1068 (or (and keybinding (key-description keybinding))
1069 (and key (concat key yas-trigger-symbol))))))
1070 (unless (yas--template-menu-managed-by-yas-define-menu template)
1072 (yas--menu-keymap-get-create (yas--table-mode table)
1073 (mapcar #'yas--table-mode
1074 (yas--table-parents table))))
1075 (group (yas--template-group template)))
1076 ;; Remove from menu keymap
1078 (assert menu-keymap)
1079 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1081 ;; Add necessary subgroups as necessary.
1083 (dolist (subgroup group)
1084 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1085 (unless (and subgroup-keymap
1086 (keymapp subgroup-keymap))
1087 (setq subgroup-keymap (make-sparse-keymap))
1088 (define-key menu-keymap (vector (make-symbol subgroup))
1089 `(menu-item ,subgroup ,subgroup-keymap)))
1090 (setq menu-keymap subgroup-keymap)))
1092 ;; Add this entry to the keymap
1094 (define-key menu-keymap
1095 (vector (make-symbol (yas--template-uuid template)))
1096 (car (yas--template-menu-binding-pair template))))))
1098 (defun yas--namehash-templates-alist (namehash)
1099 "Return NAMEHASH as an alist."
1101 (maphash #'(lambda (k v)
1102 (push (cons k v) alist))
1106 (defun yas--fetch (table key)
1107 "Fetch templates in TABLE by KEY.
1109 Return a list of cons (NAME . TEMPLATE) where NAME is a
1110 string and TEMPLATE is a `yas--template' structure."
1111 (let* ((keyhash (yas--table-hash table))
1112 (namehash (and keyhash (gethash key keyhash))))
1114 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1117 ;;; Filtering/condition logic
1119 (defun yas--eval-condition (condition)
1126 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1130 (defun yas--filter-templates-by-condition (templates)
1131 "Filter the templates using the applicable condition.
1133 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1134 string and TEMPLATE is a `yas--template' structure.
1136 This function implements the rules described in
1137 `yas-buffer-local-condition'. See that variables documentation."
1138 (let ((requirement (yas--require-template-specific-condition-p)))
1139 (if (eq requirement 'always)
1141 (remove-if-not #'(lambda (pair)
1142 (yas--template-can-expand-p
1143 (yas--template-condition (cdr pair)) requirement))
1146 (defun yas--require-template-specific-condition-p ()
1147 "Decides if this buffer requests/requires snippet-specific
1148 conditions to filter out potential expansions."
1149 (if (eq 'always yas-buffer-local-condition)
1151 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1152 (yas--eval-condition yas-buffer-local-condition))
1153 yas-buffer-local-condition)))
1154 (when local-condition
1155 (if (eq local-condition t)
1157 (and (consp local-condition)
1158 (eq 'require-snippet-condition (car local-condition))
1159 (symbolp (cdr local-condition))
1160 (cdr local-condition)))))))
1162 (defun yas--template-can-expand-p (condition requirement)
1163 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1164 (let* ((result (or (null condition)
1165 (yas--eval-condition condition))))
1166 (cond ((eq requirement t)
1169 (eq requirement result)))))
1171 (defun yas--all-parents (mode)
1172 "Returns a list of all parent modes of MODE."
1173 (or (gethash mode yas--ancestors)
1175 (labels ((yas--all-parents-1
1177 (cond ((memq m seen)
1179 "Cyclic parenthood: mode %s has already seen as a parent of mode %s"
1183 (let* ((parents (gethash m yas--parents)))
1184 (setq seen (append seen parents))
1185 (append parents (mapcan #'yas--all-parents-1 parents)))))))
1186 (puthash mode (yas--all-parents-1 mode)
1189 (defun yas--table-templates (table)
1192 (maphash #'(lambda (key namehash)
1193 (maphash #'(lambda (name template)
1194 (push (cons name template) acc))
1196 (yas--table-hash table))
1197 (yas--filter-templates-by-condition acc))))
1199 (defun yas--current-key ()
1200 "Get the key under current position. A key is used to find
1201 the template of a snippet in the current snippet-table."
1202 (let ((start (point))
1204 (syntaxes yas-key-syntaxes)
1208 (while (and (not done) syntaxes)
1209 (setq syntax (car syntaxes))
1210 (setq syntaxes (cdr syntaxes))
1212 (skip-syntax-backward syntax)
1213 (setq start (point)))
1215 (mapcan #'(lambda (table)
1216 (yas--fetch table (buffer-substring-no-properties start end)))
1217 (yas--get-snippet-tables)))
1226 (defun yas--table-all-keys (table)
1227 "Get trigger keys of all active snippets in TABLE."
1229 (maphash #'(lambda (key namehash)
1230 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1232 (yas--table-hash table))
1235 (defun yas--table-mode (table)
1236 (intern (yas--table-name table)))
1239 ;;; Internal functions and macros:
1241 (defun yas--real-mode? (mode)
1242 "Try to find out if MODE is a real mode.
1244 The MODE bound to a function (like `c-mode') is considered real
1245 mode. Other well known mode like `ruby-mode' which is not part of
1246 Emacs might not bound to a function until it is loaded. So
1247 yasnippet keeps a list of modes like this to help the judgment."
1249 (find mode yas--known-modes)))
1251 (defun yas--eval-lisp (form)
1252 "Evaluate FORM and convert the result to string."
1253 (let ((retval (catch 'yas--exception
1259 (let ((result (eval form)))
1261 (format "%s" result))))))
1262 (error (if yas-good-grace
1263 (yas--format "elisp error! %s" (error-message-string err))
1264 (error (yas--format "elisp error: %s"
1265 (error-message-string err)))))))))
1266 (when (and (consp retval)
1267 (eq 'yas--exception (car retval)))
1268 (error (cdr retval)))
1271 (defun yas--eval-lisp-no-saves (form)
1274 (error (if yas-good-grace
1275 (yas--format "elisp error! %s" (error-message-string err))
1276 (error (yas--format "elisp error: %s"
1277 (error-message-string err)))))))
1279 (defun yas--read-lisp (string &optional nil-on-error)
1280 "Read STRING as a elisp expression and return it.
1282 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1283 return an expression that when evaluated will issue an error."
1286 (error (and (not nil-on-error)
1287 `(error (error-message-string ,err))))))
1289 (defun yas--read-keybinding (keybinding)
1290 "Read KEYBINDING as a snippet keybinding, return a vector."
1291 (when (and keybinding
1292 (not (string-match "keybinding" keybinding)))
1294 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1296 (read-kbd-macro keybinding 'need-vector))))
1299 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1300 keybinding (error-message-string err))
1303 (defvar yas-extra-modes nil
1304 "If non-nil, also lookup snippets for this/these modes.
1306 Can be a symbol or a list of symbols.
1308 This variable probably makes more sense as buffer-local, so
1309 ensure your use `make-local-variable' when you set it.")
1310 (defun yas-extra-modes ()
1311 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1312 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1314 (defun yas--table-get-create (mode)
1315 "Get or create the snippet table corresponding to MODE."
1316 (let ((table (gethash mode
1319 (setq table (yas--make-snippet-table (symbol-name mode)))
1320 (puthash mode table yas--tables)
1321 (push (cons (intern (format "yas--direct-%s" mode))
1322 (yas--table-direct-keymap table))
1323 yas--direct-keymaps))
1326 (defun yas--get-snippet-tables ()
1327 "Get snippet tables for current buffer.
1329 Return a list of `yas--table' objects. The list of modes to
1330 consider is returned by `yas--modes-to-activate'"
1332 (mapcar #'(lambda (mode-name)
1333 (gethash mode-name yas--tables))
1334 (yas--modes-to-activate))))
1336 (defun yas--menu-keymap-get-create (mode &optional parents)
1337 "Get or create the menu keymap for MODE and its PARENTS.
1339 This may very well create a plethora of menu keymaps and arrange
1340 them all in `yas--menu-table'"
1341 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1342 (puthash mode (make-sparse-keymap) yas--menu-table))))
1343 (mapc #'yas--menu-keymap-get-create parents)
1344 (define-key yas--minor-mode-menu (vector mode)
1345 `(menu-item ,(symbol-name mode) ,menu-keymap
1346 :visible (yas--show-menu-p ',mode)))
1350 (defmacro yas--called-interactively-p (&optional kind)
1351 "A backward-compatible version of `called-interactively-p'.
1353 Optional KIND is as documented at `called-interactively-p'
1354 in GNU Emacs 24.1 or higher."
1355 (if (string< emacs-version "24.1")
1356 '(called-interactively-p)
1357 `(called-interactively-p ,kind)))
1360 (defun yas--call-with-temporary-redefinitions (function
1361 &rest function-names-and-overriding-functions)
1362 (let* ((overrides (remove-if-not #'(lambda (fdef)
1363 (fboundp (first fdef)))
1364 function-names-and-overriding-functions))
1365 (definition-names (mapcar #'first overrides))
1366 (overriding-functions (mapcar #'second overrides))
1367 (saved-functions (mapcar #'symbol-function definition-names)))
1368 ;; saving all definitions before overriding anything ensures FDEFINITION
1369 ;; errors don't cause accidental permanent redefinitions.
1371 (labels ((set-fdefinitions (names functions)
1372 (loop for name in names
1374 do (fset name fn))))
1375 (set-fdefinitions definition-names overriding-functions)
1376 (unwind-protect (funcall function)
1377 (set-fdefinitions definition-names saved-functions)))))
1380 (defmacro yas--with-temporary-redefinitions (fdefinitions &rest body)
1381 ;; "Temporarily (but globally) redefine each function in FDEFINITIONS.
1382 ;; E.g.: (yas--with-temporary-redefinitions ((foo (x) ...)
1384 ;; ;; code that eventually calls foo, bar of (setf foo)
1386 `(yas--call-with-temporary-redefinitions
1388 ,@(mapcar #'(lambda (thingy)
1389 `(list ',(first thingy)
1390 (lambda ,@(rest thingy))))
1393 (put 'yas--with-temporary-redefinitions 'lisp-indent-function 1)
1394 (put 'yas--with-temporary-redefinitions 'edebug-form-spec '((&rest (defun*)) cl-declarations body))
1397 ;;; Template-related and snippet loading functions
1399 (defun yas--parse-template (&optional file)
1400 "Parse the template in the current buffer.
1402 Optional FILE is the absolute file name of the file being
1405 Optional GROUP is the group where the template is to go,
1406 otherwise we attempt to calculate it from FILE.
1408 Return a snippet-definition, i.e. a list
1410 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1412 If the buffer contains a line of \"# --\" then the contents above
1413 this line are ignored. Directives can set most of these with the syntax:
1415 # directive-name : directive-value
1417 Here's a list of currently recognized directives:
1428 (goto-char (point-min))
1429 (let* ((type 'snippet)
1431 (file-name-nondirectory file)))
1437 (yas--calculate-group file)))
1441 (if (re-search-forward "^# --\n" nil t)
1442 (progn (setq template
1443 (buffer-substring-no-properties (point)
1445 (setq bound (point))
1446 (goto-char (point-min))
1447 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1448 (when (string= "uuid" (match-string-no-properties 1))
1449 (setq uuid (match-string-no-properties 2)))
1450 (when (string= "type" (match-string-no-properties 1))
1451 (setq type (if (string= "command" (match-string-no-properties 2))
1454 (when (string= "key" (match-string-no-properties 1))
1455 (setq key (match-string-no-properties 2)))
1456 (when (string= "name" (match-string-no-properties 1))
1457 (setq name (match-string-no-properties 2)))
1458 (when (string= "condition" (match-string-no-properties 1))
1459 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1460 (when (string= "group" (match-string-no-properties 1))
1461 (setq group (match-string-no-properties 2)))
1462 (when (string= "expand-env" (match-string-no-properties 1))
1463 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1465 (when (string= "binding" (match-string-no-properties 1))
1466 (setq binding (match-string-no-properties 2)))))
1468 (buffer-substring-no-properties (point-min) (point-max))))
1469 (unless (or key binding)
1470 (setq key (and file (file-name-nondirectory file))))
1471 (when (eq type 'command)
1472 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1474 (setq group (split-string group "\\.")))
1475 (list key template name condition group expand-env file binding uuid)))
1477 (defun yas--calculate-group (file)
1478 "Calculate the group for snippet file path FILE."
1479 (let* ((dominating-dir (locate-dominating-file file
1480 ".yas-make-groups"))
1481 (extra-path (and dominating-dir
1482 (replace-regexp-in-string (concat "^"
1483 (expand-file-name dominating-dir))
1485 (expand-file-name file))))
1486 (extra-dir (and extra-path
1487 (file-name-directory extra-path)))
1488 (group (and extra-dir
1489 (replace-regexp-in-string "/"
1491 (directory-file-name extra-dir)))))
1494 (defun yas--subdirs (directory &optional filep)
1495 "Return subdirs or files of DIRECTORY according to FILEP."
1496 (remove-if (lambda (file)
1497 (or (string-match "^\\."
1498 (file-name-nondirectory file))
1499 (string-match "^#.*#$"
1500 (file-name-nondirectory file))
1502 (file-name-nondirectory file))
1504 (file-directory-p file)
1505 (not (file-directory-p file)))))
1506 (directory-files directory t)))
1508 (defun yas--make-menu-binding (template)
1509 (let ((mode (yas--table-mode (yas--template-table template))))
1510 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1512 (defun yas--expand-or-visit-from-menu (mode uuid)
1513 (let* ((table (yas--table-get-create mode))
1514 (yas--current-template (and table
1515 (gethash uuid (yas--table-uuidhash table)))))
1516 (when yas--current-template
1517 (if yas-visit-from-menu
1518 (yas--visit-snippet-file-1 yas--current-template)
1519 (let ((where (if (region-active-p)
1520 (cons (region-beginning) (region-end))
1521 (cons (point) (point)))))
1522 (yas-expand-snippet (yas--template-content yas--current-template)
1525 (yas--template-expand-env yas--current-template)))))))
1527 (defun yas--key-from-desc (text)
1528 "Return a yasnippet key from a description string TEXT."
1529 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1532 ;;; Popping up for keys and templates
1534 (defvar yas--x-pretty-prompt-templates nil
1535 "If non-nil, attempt to prompt for templates like TextMate.")
1538 (defun yas--prompt-for-template (templates &optional prompt)
1539 "Interactively choose a template from the list TEMPLATES.
1541 TEMPLATES is a list of `yas--template'.
1543 Optional PROMPT sets the prompt to use."
1546 (sort templates #'(lambda (t1 t2)
1547 (< (length (yas--template-name t1))
1548 (length (yas--template-name t2))))))
1549 (if yas--x-pretty-prompt-templates
1550 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1551 (some #'(lambda (fn)
1552 (funcall fn (or prompt "Choose a snippet: ")
1554 #'yas--template-name))
1555 yas-prompt-functions))))
1557 (defun yas--prompt-for-keys (keys &optional prompt)
1558 "Interactively choose a template key from the list KEYS.
1560 Optional PROMPT sets the prompt to use."
1562 (some #'(lambda (fn)
1563 (funcall fn (or prompt "Choose a snippet key: ") keys))
1564 yas-prompt-functions)))
1566 (defun yas--prompt-for-table (tables &optional prompt)
1567 "Interactively choose a table from the list TABLES.
1569 Optional PROMPT sets the prompt to use."
1571 (some #'(lambda (fn)
1572 (funcall fn (or prompt "Choose a snippet table: ")
1575 yas-prompt-functions)))
1577 (defun yas-x-prompt (prompt choices &optional display-fn)
1578 "Display choices in a x-window prompt."
1579 ;; FIXME: HACK: if we notice that one of the objects in choices is
1580 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1582 ;; This would be better implemented by passing CHOICES as a
1583 ;; structured tree rather than a list. Modifications would go as far
1584 ;; up as `yas--all-templates' I think.
1586 (when (and window-system choices)
1588 (let (menu d) ;; d for display
1590 (setq d (or (and display-fn (funcall display-fn c))
1593 (push (cons (concat " " d) c) menu))
1595 (push (car d) menu))))
1596 (setq menu (list prompt (push "title" menu)))
1597 (x-popup-menu (if (fboundp 'posn-at-point)
1598 (let ((x-y (posn-x-y (posn-at-point (point)))))
1599 (list (list (+ (car x-y) 10)
1607 (defun yas--x-pretty-prompt-templates (prompt templates)
1608 "Display TEMPLATES, grouping neatly by table name."
1609 (let ((organized (make-hash-table :test #'equal))
1613 (dolist (tl templates)
1614 (puthash (yas--template-table tl)
1616 (gethash (yas--template-table tl) organized))
1618 (setq more-than-one-table (> (hash-table-count organized) 1))
1619 (setq prefix (if more-than-one-table
1621 (if more-than-one-table
1622 (maphash #'(lambda (table templates)
1623 (push (yas--table-name table) menu)
1624 (dolist (tl templates)
1625 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1626 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1628 (setq menu (nreverse menu))
1629 (or (x-popup-menu (if (fboundp 'posn-at-point)
1630 (let ((x-y (posn-x-y (posn-at-point (point)))))
1631 (list (list (+ (car x-y) 10)
1635 (list prompt (push "title" menu)))
1638 (defun yas-ido-prompt (prompt choices &optional display-fn)
1639 (when (and (fboundp 'ido-completing-read)
1640 (or (>= emacs-major-version 24)
1642 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1645 (if (fboundp 'declare-function)
1646 (declare-function dropdown-list "dropdown-list")))
1648 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1649 (when (featurep 'dropdown-list)
1650 (let (formatted-choices
1654 (dolist (choice choices)
1655 (setq d (or (and display-fn (funcall display-fn choice))
1658 (push d formatted-choices)
1659 (push choice filtered-choices)))
1661 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1663 (nth n filtered-choices)
1666 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1667 (let (formatted-choices
1671 (completion-fn (or completion-fn
1672 #'completing-read)))
1673 (dolist (choice choices)
1674 (setq d (or (and display-fn (funcall display-fn choice))
1677 (push d formatted-choices)
1678 (push choice filtered-choices)))
1679 (setq chosen (and formatted-choices
1680 (funcall completion-fn prompt
1686 (let ((position (or (and chosen
1687 (position chosen formatted-choices :test #'string=))
1689 (nth position filtered-choices))))
1691 (defun yas-no-prompt (prompt choices &optional display-fn)
1695 ;;; Defining snippets
1696 ;; This consists of creating and registering `yas--template' objects in the
1700 (defun yas--define-snippets-1 (snippet snippet-table)
1701 "Helper for `yas-define-snippets'."
1702 ;; X) Calculate some more defaults on the values returned by
1703 ;; `yas--parse-template'.
1705 (let* ((file (seventh snippet))
1707 (name (or (third snippet)
1709 (file-name-directory file))))
1710 (condition (fourth snippet))
1711 (group (fifth snippet))
1712 (keybinding (yas--read-keybinding (eighth snippet)))
1713 (uuid (or (ninth snippet)
1715 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1716 (yas--make-blank-template))))
1717 ;; X) populate the template object
1719 (yas--populate-template template
1720 :table snippet-table
1722 :content (second snippet)
1725 :condition condition
1726 :expand-env (sixth snippet)
1727 :file (seventh snippet)
1728 :keybinding keybinding
1730 ;; X) Update this template in the appropriate table. This step
1731 ;; also will take care of adding the key indicators in the
1732 ;; templates menu entry, if any
1734 (yas--update-template snippet-table template)
1735 ;; X) Return the template
1740 (defun yas-define-snippets (mode snippets)
1741 "Define SNIPPETS for MODE.
1743 SNIPPETS is a list of snippet definitions, each taking the
1746 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1748 Within these, only KEY and TEMPLATE are actually mandatory.
1750 TEMPLATE might be a lisp form or a string, depending on whether
1751 this is a snippet or a snippet-command.
1753 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1754 been `yas--read-lisp'-ed and will eventually be
1755 `yas--eval-lisp'-ed.
1757 The remaining elements are strings.
1759 FILE is probably of very little use if you're programatically
1762 UUID is the snippets \"unique-id\". Loading a second snippet file
1763 with the same uuid replaced the previous snippet.
1765 You can use `yas--parse-template' to return such lists based on
1766 the current buffers contents."
1767 (let ((snippet-table (yas--table-get-create mode))
1769 (dolist (snippet snippets)
1770 (setq template (yas--define-snippets-1 snippet
1775 ;;; Loading snippets from files
1777 (defun yas--load-yas-setup-file (file)
1778 (load file 'noerror))
1780 (defun yas--define-parents (mode parents)
1781 "Add PARENTS to the list of MODE's parents."
1782 (puthash mode (remove-duplicates
1784 (gethash mode yas--parents)))
1787 (defun yas-load-directory (top-level-dir &optional use-jit)
1788 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1790 Below TOP-LEVEL-DIR each directory should be a mode name.
1792 Optional USE-JIT use jit-loading of snippets."
1793 (interactive "DSelect the root directory: ")
1794 (unless yas-snippet-dirs
1795 (setq yas-snippet-dirs top-level-dir))
1796 (dolist (dir (yas--subdirs top-level-dir))
1797 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1798 (concat dir "/dummy")))
1799 (mode-sym (car major-mode-and-parents))
1800 (parents (cdr major-mode-and-parents)))
1801 ;; Attention: The parents and the menus are already defined
1802 ;; here, even if the snippets are later jit-loaded.
1804 ;; * We need to know the parents at this point since entering a
1805 ;; given mode should jit load for its parents
1806 ;; immediately. This could be reviewed, the parents could be
1807 ;; discovered just-in-time-as well
1809 ;; * We need to create the menus here to support the `full'
1810 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1812 (yas--define-parents mode-sym parents)
1813 (yas--menu-keymap-get-create mode-sym)
1814 (let ((form `(yas--load-directory-1 ,dir
1818 (not (some #'(lambda (buffer)
1819 (with-current-buffer buffer
1820 (when (eq major-mode mode-sym)
1821 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1824 (yas--schedule-jit mode-sym form)
1826 (when (yas--called-interactively-p 'interactive)
1827 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1829 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1830 "Recursively load snippet templates from DIRECTORY."
1831 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1832 (if (and (not no-compiled-snippets)
1833 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1834 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1835 (yas--message 2 "Loading snippet files from %s" directory)
1836 (yas--load-directory-2 directory mode-sym))))
1838 (defun yas--load-directory-2 (directory mode-sym)
1839 ;; Load .yas-setup.el files wherever we find them
1841 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1842 (let* ((default-directory directory)
1844 ;; load the snippet files
1847 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1848 (when (file-readable-p file)
1849 (insert-file-contents file nil nil nil t)
1850 (push (yas--parse-template file)
1853 (yas-define-snippets mode-sym
1855 ;; now recurse to a lower level
1857 (dolist (subdir (yas--subdirs directory))
1858 (yas--load-directory-2 subdir
1861 (defun yas--load-snippet-dirs (&optional nojit)
1862 "Reload the directories listed in `yas-snippet-dirs' or
1863 prompt the user to select one."
1865 (if yas-snippet-dirs
1866 (dolist (directory (reverse (yas-snippet-dirs)))
1867 (cond ((file-directory-p directory)
1868 (yas-load-directory directory (not nojit))
1870 (yas--message 3 "Loaded %s" directory)
1871 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1873 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1874 (call-interactively 'yas-load-directory))
1877 (defun yas-reload-all (&optional interactive)
1878 "Reload all snippets and rebuild the YASnippet menu.
1880 When called interactively force immediate reload of all known
1881 snippets under `yas-snippet-dirs', otherwise use just-in-time
1886 (snippet-editing-buffers
1887 (remove-if-not #'(lambda (buffer)
1888 (with-current-buffer buffer yas--editing-template))
1890 ;; Warn if there are buffers visiting snippets, since reloading will break
1891 ;; any on-line editing of those buffers.
1893 (when snippet-editing-buffers
1895 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1896 (mapc #'kill-buffer snippet-editing-buffers)
1897 (yas--message 1 "Aborted reload...")
1899 ;; in a non-interactive use, at least set
1900 ;; `yas--editing-template' to nil, make it guess it next time around
1901 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1903 ;; Empty all snippet tables and parenting info
1905 (setq yas--tables (make-hash-table))
1906 (setq yas--parents (make-hash-table))
1907 (setq yas--ancestors (make-hash-table))
1909 ;; Before killing `yas--menu-table' use its keys to cleanup the
1910 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1911 ;; up `yas-minor-mode-map', which points to it)
1913 (maphash #'(lambda (menu-symbol keymap)
1914 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1916 ;; Now empty `yas--menu-table' as well
1917 (setq yas--menu-table (make-hash-table))
1919 ;; Cancel all pending 'yas--scheduled-jit-loads'
1921 (setq yas--scheduled-jit-loads (make-hash-table))
1923 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1924 ;; the user to select one.
1926 (setq errors (yas--load-snippet-dirs interactive))
1927 ;; Reload the direct keybindings
1929 (yas-direct-keymaps-reload)
1931 (yas--message 3 "Reloaded everything%s...%s."
1932 (if interactive "" " (snippets will load just-in-time)")
1933 (if errors " (some errors, check *Messages*)" "")))))
1935 (defun yas--load-pending-jits ()
1936 (dolist (mode (yas--modes-to-activate))
1937 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1938 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1939 (dolist (form forms)
1940 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1942 (remhash mode yas--scheduled-jit-loads))))
1944 ;; (when (<= emacs-major-version 22)
1945 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1947 (defun yas--quote-string (string)
1948 "Escape and quote STRING.
1949 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1951 (replace-regexp-in-string "[\\\"]"
1957 ;;; Snippet compilation function
1959 (defun yas--initialize ()
1960 "For backward compatibility, enable `yas-minor-mode' globally."
1961 (yas-global-mode 1))
1963 (defun yas-compile-directory (top-level-dir)
1964 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1966 This works by stubbing a few functions, then calling
1967 `yas-load-directory'."
1968 (interactive "DTop level snippet directory?")
1969 (yas--with-temporary-redefinitions
1970 ((yas--load-yas-setup-file
1972 (let ((elfile (concat file ".el")))
1973 (when (file-exists-p elfile)
1974 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1975 (insert-file-contents elfile)
1976 (goto-char (point-max))
1978 (yas-define-snippets
1980 (insert ";;; Snippet definitions:\n;;;\n")
1981 (let ((literal-snippets (list))
1983 (dolist (snippet snippets)
1984 (let ((key (first snippet))
1985 (template-content (second snippet))
1986 (name (third snippet))
1987 (condition (fourth snippet))
1988 (group (fifth snippet))
1989 (expand-env (sixth snippet))
1990 (file nil) ;; (seventh snippet)) ;; omit on purpose
1991 (binding (eighth snippet))
1992 (uuid (ninth snippet)))
2003 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
2005 (yas--load-directory-1
2006 (dir mode parents &rest ignore)
2007 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
2008 (with-temp-file output-file
2009 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
2010 (yas--load-directory-2 dir mode)
2011 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
2012 (yas-load-directory top-level-dir nil)))
2014 (defun yas-recompile-all ()
2015 "Compile every dir in `yas-snippet-dirs'."
2017 (mapc #'yas-compile-directory (yas-snippet-dirs)))
2023 (defvar yas--scheduled-jit-loads (make-hash-table)
2024 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
2026 (defun yas--schedule-jit (mode form)
2029 (gethash mode yas--scheduled-jit-loads))
2030 yas--scheduled-jit-loads))
2034 ;;; Some user level functions
2038 (message (concat "yasnippet (version "
2040 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2043 ;;; Apropos snippet menu:
2045 ;; The snippet menu keymaps are store by mode in hash table called
2046 ;; `yas--menu-table'. They are linked to the main menu in
2047 ;; `yas--menu-keymap-get-create' and are initially created empty,
2048 ;; reflecting the table hierarchy.
2050 ;; They can be populated in two mutually exclusive ways: (1) by
2051 ;; reading `yas--template-group', which in turn is populated by the "#
2052 ;; group:" directives of the snippets or the ".yas-make-groups" file
2053 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2054 ;; menu structure based on snippets uuids.
2056 ;; Both situations are handled in `yas--update-template-menu', which
2057 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2058 ;; that can tell between the two situations.
2062 ;; * if `yas-define-menu' is used it must run before
2063 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2064 ;; duplicate entries. The `yas--template' objects are created in
2065 ;; `yas-define-menu', holding nothing but the menu entry,
2066 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2067 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2068 ;; part is then stored in the menu keymap itself which make the item
2069 ;; appear to the user. These limitations could probably be revised.
2071 ;; * The `yas--template-perm-group' slot is only used in
2072 ;; `yas-describe-tables'.
2074 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2075 "Get TEMPLATE's menu binding or assign it a new one.
2077 TYPE may be `:stay', signaling this menu binding should be
2078 static in the menu."
2079 (or (yas--template-menu-binding-pair template)
2080 (let ((key (yas--template-key template))
2081 (keybinding (yas--template-keybinding template)))
2082 (setf (yas--template-menu-binding-pair template)
2083 (cons `(menu-item ,(or (yas--template-name template)
2084 (yas--template-uuid template))
2085 ,(yas--make-menu-binding template)
2088 (defun yas--template-menu-managed-by-yas-define-menu (template)
2089 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2090 (cdr (yas--template-menu-binding-pair template)))
2093 (defun yas--show-menu-p (mode)
2094 (cond ((eq yas-use-menu 'abbreviate)
2096 (mapcar #'(lambda (table)
2097 (yas--table-mode table))
2098 (yas--get-snippet-tables))))
2099 ((eq yas-use-menu 'full)
2101 ((eq yas-use-menu t)
2104 (defun yas--delete-from-keymap (keymap uuid)
2105 "Recursively delete items with UUID from KEYMAP and its submenus."
2107 ;; XXX: This used to skip any submenus named \"parent mode\"
2109 ;; First of all, recursively enter submenus, i.e. the tree is
2110 ;; searched depth first so that stale submenus can be found in the
2113 (mapc #'(lambda (item)
2114 (when (and (listp (cdr item))
2115 (keymapp (third (cdr item))))
2116 (yas--delete-from-keymap (third (cdr item)) uuid)))
2118 ;; Set the uuid entry to nil
2120 (define-key keymap (vector (make-symbol uuid)) nil)
2121 ;; Destructively modify keymap
2123 (setcdr keymap (delete-if #'(lambda (item)
2124 (or (null (cdr item))
2125 (and (keymapp (third (cdr item)))
2126 (null (cdr (third (cdr item)))))))
2129 (defun yas-define-menu (mode menu &optional omit-items)
2130 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2132 MENU is a list, its elements can be:
2134 - (yas-item UUID) : Creates an entry the snippet identified with
2135 UUID. The menu entry for a snippet thus identified is
2136 permanent, i.e. it will never move (be reordered) in the menu.
2138 - (yas-separator) : Creates a separator
2140 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2141 SUBMENU has the same form as MENU. NAME is also added to the
2142 list of groups of the snippets defined thereafter.
2144 OMIT-ITEMS is a list of snippet uuid's that will always be
2145 omitted from MODE's menu, even if they're manually loaded.
2147 This function does nothing if `yas-use-menu' is nil."
2149 (let* ((table (yas--table-get-create mode))
2150 (hash (yas--table-uuidhash table)))
2151 (yas--define-menu-1 table
2152 (yas--menu-keymap-get-create mode)
2155 (dolist (uuid omit-items)
2156 (let ((template (or (gethash uuid hash)
2157 (yas--populate-template (puthash uuid
2158 (yas--make-blank-template)
2162 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2164 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2165 "Helper for `yas-define-menu'."
2166 (dolist (e (reverse menu))
2167 (cond ((eq (first e) 'yas-item)
2168 (let ((template (or (gethash (second e) uuidhash)
2169 (yas--populate-template (puthash (second e)
2170 (yas--make-blank-template)
2173 :perm-group group-list
2174 :uuid (second e)))))
2175 (define-key menu-keymap (vector (gensym))
2176 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2177 ((eq (first e) 'yas-submenu)
2178 (let ((subkeymap (make-sparse-keymap)))
2179 (define-key menu-keymap (vector (gensym))
2180 `(menu-item ,(second e) ,subkeymap))
2181 (yas--define-menu-1 table
2185 (append group-list (list (second e))))))
2186 ((eq (first e) 'yas-separator)
2187 (define-key menu-keymap (vector (gensym))
2188 '(menu-item "----")))
2190 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2192 (defun yas--define (mode key template &optional name condition group)
2193 "Define a snippet. Expanding KEY into TEMPLATE.
2195 NAME is a description to this template. Also update the menu if
2196 `yas-use-menu' is t. CONDITION is the condition attached to
2197 this snippet. If you attach a condition to a snippet, then it
2198 will only be expanded when the condition evaluated to non-nil."
2199 (yas-define-snippets mode
2200 (list (list key template name condition group))))
2202 (defun yas-hippie-try-expand (first-time?)
2203 "Integrate with hippie expand.
2205 Just put this function in `hippie-expand-try-functions-list'."
2206 (when yas-minor-mode
2207 (if (not first-time?)
2208 (let ((yas-fallback-behavior 'return-nil))
2214 ;;; Apropos condition-cache:
2219 (defvar yas--condition-cache-timestamp nil)
2220 (defmacro yas-define-condition-cache (func doc &rest body)
2221 "Define a function FUNC with doc DOC and body BODY, BODY is
2222 executed at most once every snippet expansion attempt, to check
2223 expansion conditions.
2225 It doesn't make any sense to call FUNC programatically."
2226 `(defun ,func () ,(if (and doc
2229 "\n\nFor use in snippets' conditions. Within each
2230 snippet-expansion routine like `yas-expand', computes actual
2231 value for the first time then always returns a cached value.")
2232 (setq body (cons doc body))
2234 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2235 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2236 (cdr timestamp-and-value)
2237 (let ((new-value (progn
2240 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2243 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2244 (defun yas-expand-from-trigger-key (&optional field)
2245 "Expand a snippet before point.
2247 If no snippet expansion is possible, fall back to the behaviour
2248 defined in `yas-fallback-behavior'.
2250 Optional argument FIELD is for non-interactive use and is an
2251 object satisfying `yas--field-p' to restrict the expansion to."
2253 (setq yas--condition-cache-timestamp (current-time))
2254 (let (templates-and-pos)
2255 (unless (and yas-expand-only-for-last-commands
2256 (not (member last-command yas-expand-only-for-last-commands)))
2257 (setq templates-and-pos (if field
2259 (narrow-to-region (yas--field-start field)
2260 (yas--field-end field))
2262 (yas--current-key))))
2263 (if (and templates-and-pos
2264 (first templates-and-pos))
2265 (yas--expand-or-prompt-for-template (first templates-and-pos)
2266 (second templates-and-pos)
2267 (third templates-and-pos))
2268 (yas--fallback 'trigger-key))))
2270 (defun yas-expand-from-keymap ()
2271 "Directly expand some snippets, searching `yas--direct-keymaps'.
2273 If expansion fails, execute the previous binding for this key"
2275 (setq yas--condition-cache-timestamp (current-time))
2276 (let* ((yas--prefix current-prefix-arg)
2277 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2278 universal-argument-num-events
2280 (templates (mapcan #'(lambda (table)
2281 (yas--fetch table vec))
2282 (yas--get-snippet-tables))))
2284 (yas--expand-or-prompt-for-template templates)
2285 (let ((yas-fallback-behavior 'call-other-command))
2288 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2289 "Expand one of TEMPLATES from START to END.
2291 Prompt the user if TEMPLATES has more than one element, else
2292 expand immediately. Common gateway for
2293 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2294 (let ((yas--current-template (or (and (rest templates) ;; more than one
2295 (yas--prompt-for-template (mapcar #'cdr templates)))
2297 (when yas--current-template
2298 (yas-expand-snippet (yas--template-content yas--current-template)
2301 (yas--template-expand-env yas--current-template)))))
2303 ;; Apropos the trigger key and the fallback binding:
2305 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2306 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2307 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2308 ;; improve this explanation.
2310 (defun yas--fallback (&optional from-trigger-key-p)
2311 "Fallback after expansion has failed.
2313 Common gateway for `yas-expand-from-trigger-key' and
2314 `yas-expand-from-keymap'."
2315 (cond ((eq yas-fallback-behavior 'return-nil)
2318 ((eq yas-fallback-behavior 'call-other-command)
2319 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2320 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2321 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2322 (setq this-original-command beyond-yasnippet)
2323 (call-interactively beyond-yasnippet)))
2324 ((and (listp yas-fallback-behavior)
2325 (cdr yas-fallback-behavior)
2326 (eq 'apply (car yas-fallback-behavior)))
2327 (if (cddr yas-fallback-behavior)
2328 (apply (cadr yas-fallback-behavior)
2329 (cddr yas-fallback-behavior))
2330 (when (commandp (cadr yas-fallback-behavior))
2331 (setq this-command (cadr yas-fallback-behavior))
2332 (call-interactively (cadr yas-fallback-behavior)))))
2334 ;; also return nil if all the other fallbacks have failed
2337 (defun yas--keybinding-beyond-yasnippet ()
2339 (let* ((yas-minor-mode nil)
2340 (yas--direct-keymaps nil)
2341 (keys (this-single-command-keys)))
2342 (or (key-binding keys t)
2343 (key-binding (yas--fallback-translate-input keys) t))))
2345 (defun yas--fallback-translate-input (keys)
2346 "Emulate `read-key-sequence', at least what I think it does.
2348 Keys should be an untranslated key vector. Returns a translated
2349 vector of keys. FIXME not thoroughly tested"
2352 (while (< i (length keys))
2354 (translated local-function-key-map))
2355 (while (and (< j (length keys))
2357 (keymapp translated))
2358 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2360 (setq retval (vconcat retval (cond ((symbolp translated)
2362 ((vectorp translated)
2365 (substring keys i j)))))
2370 ;;; Utils for snippet development:
2372 (defun yas--all-templates (tables)
2373 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2375 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2376 `yas-buffer-local-condition'"
2377 (when yas-choose-tables-first
2378 (setq tables (list (yas--prompt-for-table tables))))
2380 (if yas-choose-keys-first
2381 (let ((key (yas--prompt-for-keys
2382 (mapcan #'yas--table-all-keys tables))))
2384 (mapcan #'(lambda (table)
2385 (yas--fetch table key))
2387 (remove-duplicates (mapcan #'yas--table-templates tables)
2390 (defun yas-insert-snippet (&optional no-condition)
2391 "Choose a snippet to expand, pop-up a list of choices according
2392 to `yas--prompt-function'.
2394 With prefix argument NO-CONDITION, bypass filtering of snippets
2397 (setq yas--condition-cache-timestamp (current-time))
2398 (let* ((yas-buffer-local-condition (or (and no-condition
2400 yas-buffer-local-condition))
2401 (templates (yas--all-templates (yas--get-snippet-tables)))
2402 (yas--current-template (and templates
2403 (or (and (rest templates) ;; more than one template for same key
2404 (yas--prompt-for-template templates))
2406 (where (if (region-active-p)
2407 (cons (region-beginning) (region-end))
2408 (cons (point) (point)))))
2409 (if yas--current-template
2410 (yas-expand-snippet (yas--template-content yas--current-template)
2413 (yas--template-expand-env yas--current-template))
2414 (yas--message 3 "No snippets can be inserted here!"))))
2416 (defun yas-visit-snippet-file ()
2417 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2419 Only success if selected snippet was loaded from a file. Put the
2420 visited file in `snippet-mode'."
2422 (let* ((yas-buffer-local-condition 'always)
2423 (templates (yas--all-templates (yas--get-snippet-tables)))
2424 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2425 (template (and templates
2426 (or (yas--prompt-for-template templates
2427 "Choose a snippet template to edit: ")
2431 (yas--visit-snippet-file-1 template)
2432 (message "No snippets tables active!"))))
2434 (defun yas--visit-snippet-file-1 (template)
2435 "Helper for `yas-visit-snippet-file'."
2436 (let ((file (yas--template-file template)))
2437 (cond ((and file (file-readable-p file))
2438 (find-file-other-window file)
2440 (set (make-local-variable 'yas--editing-template) template))
2442 (message "Original file %s no longer exists!" file))
2444 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2445 (let ((type 'snippet))
2446 (when (listp (yas--template-content template))
2447 (insert (format "# type: command\n"))
2448 (setq type 'command))
2449 (insert (format "# key: %s\n" (yas--template-key template)))
2450 (insert (format "# name: %s\n" (yas--template-name template)))
2451 (when (yas--template-keybinding template)
2452 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2453 (when (yas--template-expand-env template)
2454 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2455 (when (yas--template-condition template)
2456 (insert (format "# condition: %s\n" (yas--template-condition template))))
2458 (insert (if (eq type 'command)
2459 (pp-to-string (yas--template-content template))
2460 (yas--template-content template))))
2462 (set (make-local-variable 'yas--editing-template) template)))))
2464 (defun yas--guess-snippet-directories-1 (table)
2465 "Guesses possible snippet subdirectories for TABLE."
2466 (cons (yas--table-name table)
2467 (mapcan #'(lambda (parent)
2468 (yas--guess-snippet-directories-1
2470 (yas--table-parents table))))
2472 (defun yas--guess-snippet-directories (&optional table)
2473 "Try to guess suitable directories based on the current active
2474 tables (or optional TABLE).
2476 Returns a list of elements (TABLE . DIRS) where TABLE is a
2477 `yas--table' object and DIRS is a list of all possible directories
2478 where snippets of table might exist."
2479 (let ((main-dir (replace-regexp-in-string
2481 (or (first (or (yas-snippet-dirs)
2482 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2483 (tables (or (and table
2485 (yas--get-snippet-tables))))
2486 ;; HACK! the snippet table created here is actually registered!
2488 (unless (or table (gethash major-mode yas--tables))
2489 (push (yas--table-get-create major-mode)
2492 (mapcar #'(lambda (table)
2494 (mapcar #'(lambda (subdir)
2495 (concat main-dir "/" subdir))
2496 (yas--guess-snippet-directories-1 table))))
2499 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2500 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2501 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2502 (let ((candidate (first (cdr table-and-dirs))))
2503 (unless (file-writable-p (file-name-directory candidate))
2504 (error (yas--format "%s is not writable." candidate)))
2505 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2507 (if (gethash (yas--table-mode (car table-and-dirs))
2511 (or main-table-string
2513 (yas--table-name (car table-and-dirs))))
2515 (make-directory candidate 'also-make-parents)
2516 ;; create the .yas-parents file here...
2519 (defun yas-new-snippet (&optional no-template)
2520 "Pops a new buffer for writing a snippet.
2522 Expands a snippet-writing snippet, unless the optional prefix arg
2523 NO-TEMPLATE is non-nil."
2525 (let ((guessed-directories (yas--guess-snippet-directories)))
2527 (switch-to-buffer "*new snippet*")
2529 (kill-all-local-variables)
2532 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2533 (yas--table-mode (car d)))
2534 guessed-directories))
2535 (if (and (not no-template) yas-new-snippet-default)
2536 (yas-expand-snippet yas-new-snippet-default))))
2538 (defun yas--compute-major-mode-and-parents (file)
2539 "Given FILE, find the nearest snippet directory for a given mode.
2541 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2542 representing one or more of the mode's parents.
2544 Note that MODE-SYM need not be the symbol of a real major mode,
2545 neither do the elements of PARENTS."
2546 (let* ((file-dir (and file
2547 (directory-file-name (or (some #'(lambda (special)
2548 (locate-dominating-file file special))
2552 (directory-file-name (file-name-directory file))))))
2553 (parents-file-name (concat file-dir "/.yas-parents"))
2554 (major-mode-name (and file-dir
2555 (file-name-nondirectory file-dir)))
2556 (major-mode-sym (or (and major-mode-name
2557 (intern major-mode-name))))
2558 (parents (when (file-readable-p parents-file-name)
2562 (insert-file-contents parents-file-name)
2563 (buffer-substring-no-properties (point-min)
2565 (when major-mode-sym
2566 (cons major-mode-sym (remove major-mode-sym parents)))))
2568 (defvar yas--editing-template nil
2569 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2571 (defvar yas--current-template nil
2572 "Holds the current template being expanded into a snippet.")
2574 (defvar yas--guessed-modes nil
2575 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2577 (defun yas--read-table ()
2578 "Ask user for a snippet table, help with some guessing."
2579 (let ((prompt (if (and (featurep 'ido)
2581 'ido-completing-read 'completing-read)))
2582 (unless yas--guessed-modes
2583 (set (make-local-variable 'yas--guessed-modes)
2584 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2586 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2587 (if yas--guessed-modes
2588 (first yas--guessed-modes)
2590 (mapcar #'symbol-name yas--guessed-modes)
2595 (if (first yas--guessed-modes)
2596 (symbol-name (first yas--guessed-modes)))))))
2598 (defun yas-load-snippet-buffer (table &optional interactive)
2599 "Parse and load current buffer's snippet definition into TABLE.
2601 TABLE is a symbol naming a passed to `yas--table-get-create'.
2603 When called interactively, prompt for the table name and
2604 whether (and where) to save the snippet, then quit the window."
2605 (interactive (list (yas--read-table) t))
2607 ;; We have `yas--editing-template', this buffer's content comes from a
2608 ;; template which is already loaded and neatly positioned,...
2610 (yas--editing-template
2611 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2612 (yas--template-table yas--editing-template)))
2613 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2614 ;; value from `yas--compute-major-mode-and-parents'
2617 (unless yas--guessed-modes
2618 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2619 (let* ((table (yas--table-get-create table)))
2620 (set (make-local-variable 'yas--editing-template)
2621 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2624 (when (and interactive
2626 ;; Only offer to save this if it looks like a library or new
2627 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2628 ;; which is not the first, or from an unwritable file)
2630 (not (yas--template-file yas--editing-template))
2631 (not (file-writable-p (yas--template-file yas--editing-template)))
2632 (and (listp yas-snippet-dirs)
2633 (second yas-snippet-dirs)
2634 (not (string-match (expand-file-name (first yas-snippet-dirs))
2635 (yas--template-file yas--editing-template)))))
2636 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2637 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2639 (yas--make-directory-maybe option))))
2641 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2642 (file-name-nondirectory (yas--template-file yas--editing-template)))
2643 (yas--template-name yas--editing-template))))
2644 (write-file (concat chosen "/"
2645 (read-from-minibuffer (format "File name to create in %s? " chosen)
2646 default-file-name)))
2647 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2649 (yas--message 3 "Snippet \"%s\" loaded for %s."
2650 (yas--template-name yas--editing-template)
2651 (yas--table-name (yas--template-table yas--editing-template)))
2652 (quit-window interactive)))
2654 (defun yas-tryout-snippet (&optional debug)
2655 "Test current buffer's snippet template in other buffer."
2657 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2658 (parsed (yas--parse-template))
2659 (test-mode (or (and (car major-mode-and-parent)
2660 (fboundp (car major-mode-and-parent))
2661 (car major-mode-and-parent))
2662 (first yas--guessed-modes)
2663 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2664 (yas--current-template
2667 (yas--populate-template (yas--make-blank-template)
2668 :table nil ;; no tables for ephemeral snippets
2670 :content (second parsed)
2671 :name (third parsed)
2672 :expand-env (sixth parsed)))))
2673 (cond (yas--current-template
2674 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2675 (kill-buffer (get-buffer-create buffer-name))
2676 (switch-to-buffer (get-buffer-create buffer-name))
2677 (setq buffer-undo-list nil)
2678 (condition-case nil (funcall test-mode) (error nil))
2680 (setq buffer-read-only nil)
2681 (yas-expand-snippet (yas--template-content yas--current-template)
2684 (yas--template-expand-env yas--current-template))
2686 (require 'yasnippet-debug nil t))
2687 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2689 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2691 (defun yas-active-keys ()
2692 "Return all active trigger keys for current buffer and point."
2694 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2697 (defun yas--template-fine-group (template)
2698 (car (last (or (yas--template-group template)
2699 (yas--template-perm-group template)))))
2701 (defun yas-describe-tables (&optional choose)
2702 "Display snippets for each table."
2704 (let* ((by-name-hash (and choose
2705 (y-or-n-p "Show by namehash? ")))
2706 (buffer (get-buffer-create "*YASnippet tables*"))
2707 (active-tables (yas--get-snippet-tables))
2708 (remain-tables (let ((all))
2709 (maphash #'(lambda (k v)
2710 (unless (find v active-tables)
2714 (table-lists (list active-tables remain-tables))
2715 (original-buffer (current-buffer))
2717 (yas--condition-cache-timestamp (current-time)))
2718 (with-current-buffer buffer
2719 (setq buffer-read-only nil)
2721 (cond ((not by-name-hash)
2722 (insert "YASnippet tables: \n")
2723 (while (and table-lists
2725 (dolist (table (car table-lists))
2726 (yas--describe-pretty-table table original-buffer))
2727 (setq table-lists (cdr table-lists))
2729 (yas--create-snippet-xrefs)
2730 (display-buffer buffer)
2731 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2732 (yas--create-snippet-xrefs)
2736 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2737 (dolist (table (append active-tables remain-tables))
2738 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2740 (maphash #'(lambda (k v)
2742 (yas--table-hash table))
2744 (insert (format " key %s maps snippets: %s\n" key
2746 (maphash #'(lambda (k v)
2748 (gethash key (yas--table-hash table)))
2751 (setq buffer-read-only t))
2752 (display-buffer buffer)))
2754 (defun yas--describe-pretty-table (table &optional original-buffer)
2755 (insert (format "\nSnippet table `%s'"
2756 (yas--table-name table)))
2757 (if (yas--table-parents table)
2758 (insert (format " parents: %s\n"
2759 (mapcar #'yas--table-name
2760 (yas--table-parents table))))
2762 (insert (make-string 100 ?-) "\n")
2763 (insert "group state name key binding\n")
2764 (let ((groups-hash (make-hash-table :test #'equal)))
2765 (maphash #'(lambda (k v)
2766 (let ((group (or (yas--template-fine-group v)
2768 (when (yas--template-name v)
2770 (cons v (gethash group groups-hash))
2772 (yas--table-uuidhash table))
2774 #'(lambda (group templates)
2775 (setq group (truncate-string-to-width group 25 0 ? "..."))
2776 (insert (make-string 100 ?-) "\n")
2777 (dolist (p templates)
2778 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2782 (setq group (make-string (length group) ? ))))
2783 (condition-string (let ((condition (yas--template-condition p)))
2786 (with-current-buffer original-buffer
2787 (if (yas--eval-condition condition)
2792 (insert condition-string " ")
2794 (if (string-match "\\.\\.\\.$" name)
2798 (insert (truncate-string-to-width (or (yas--template-key p) "")
2800 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2807 ;;; User convenience functions, for using in snippet definitions
2809 (defvar yas-modified-p nil
2810 "Non-nil if field has been modified by user or transformation.")
2812 (defvar yas-moving-away-p nil
2813 "Non-nil if user is about to exit field.")
2815 (defvar yas-text nil
2816 "Contains current field text.")
2818 (defun yas-substr (str pattern &optional subexp)
2819 "Search PATTERN in STR and return SUBEXPth match.
2821 If found, the content of subexp group SUBEXP (default 0) is
2822 returned, or else the original STR will be returned."
2823 (let ((grp (or subexp 0)))
2825 (if (string-match pattern str)
2826 (match-string-no-properties grp str)
2829 (defun yas-choose-value (&rest possibilities)
2830 "Prompt for a string in POSSIBILITIES and return it.
2832 The last element of POSSIBILITIES may be a list of strings."
2833 (unless (or yas-moving-away-p
2835 (setq possibilities (nreverse possibilities))
2836 (setq possibilities (if (listp (car possibilities))
2837 (append (reverse (car possibilities)) (rest possibilities))
2839 (some #'(lambda (fn)
2840 (funcall fn "Choose: " possibilities))
2841 yas-prompt-functions)))
2843 (defun yas-key-to-value (alist)
2844 (unless (or yas-moving-away-p
2846 (let ((key (read-key-sequence "")))
2848 (or (cdr (find key alist :key #'car :test #'string=))
2851 (defun yas-throw (text)
2852 "Throw a yas--exception with TEXT as the reason."
2853 (throw 'yas--exception (cons 'yas--exception text)))
2855 (defun yas-verify-value (possibilities)
2856 "Verify that the current field value is in POSSIBILITIES.
2858 Otherwise throw exception."
2859 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2860 (yas-throw (yas--format "Field only allows %s" possibilities))))
2862 (defun yas-field-value (number)
2863 "Get the string for field with NUMBER.
2865 Use this in primary and mirror transformations to tget."
2866 (let* ((snippet (car (yas--snippets-at-point)))
2868 (yas--snippet-find-field snippet number))))
2870 (yas--field-text-for-display field))))
2873 "Return `yas-text' if that exists and is non-empty, else nil."
2875 (not (string= "" yas-text)))
2878 (defun yas-selected-text ()
2879 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2880 (if (and yas-selected-text
2881 (not (string= "" yas-selected-text)))
2884 (defun yas--get-field-once (number &optional transform-fn)
2885 (unless yas-modified-p
2887 (funcall transform-fn (yas-field-value number))
2888 (yas-field-value number))))
2890 (defun yas-default-from-field (number)
2891 (unless yas-modified-p
2892 (yas-field-value number)))
2894 (defun yas-inside-string ()
2895 "Return non-nil if the point is inside a string according to font-lock."
2896 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2898 (defun yas-unimplemented (&optional missing-feature)
2899 (if yas--current-template
2900 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2903 (yas--visit-snippet-file-1 yas--current-template))
2904 (message "No implementation. Missing %s" (or missing-feature "something"))))
2907 ;;; Snippet expansion and field management
2909 (defvar yas--active-field-overlay nil
2910 "Overlays the currently active field.")
2912 (defvar yas--field-protection-overlays nil
2913 "Two overlays protect the current active field.")
2915 (defconst yas--prefix nil
2916 "A prefix argument for expansion direct from keybindings.")
2918 (defvar yas-selected-text nil
2919 "The selected region deleted on the last snippet expansion.")
2921 (defvar yas--start-column nil
2922 "The column where the snippet expansion started.")
2924 (make-variable-buffer-local 'yas--active-field-overlay)
2925 (make-variable-buffer-local 'yas--field-protection-overlays)
2926 (put 'yas--active-field-overlay 'permanent-local t)
2927 (put 'yas--field-protection-overlays 'permanent-local t)
2929 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2935 (id (yas--snippet-next-id) :read-only t)
2936 (control-overlay nil)
2938 ;; stacked expansion: the `previous-active-field' slot saves the
2939 ;; active field where the child expansion took place
2940 previous-active-field
2943 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2946 NUMBER is the field number.
2947 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2948 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2949 MIRRORS is a list of `yas--mirror's
2950 TRANSFORM is a lisp form.
2951 MODIFIED-P is a boolean set to true once user inputs text.
2952 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2963 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2966 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2967 TRANSFORM is a lisp form.
2968 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2969 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2970 DEPTH is a count of how many nested mirrors can affect this mirror"
2977 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2981 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2982 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2984 If there is no transform for ht field, return nil.
2986 If there is a transform but it returns nil, return the empty
2987 string iff EMPTY-ON-NIL-P is true."
2988 (let* ((yas-text (yas--field-text-for-display field))
2990 (yas-modified-p (yas--field-modified-p field))
2991 (yas-moving-away-p nil)
2992 (transform (if (yas--mirror-p field-or-mirror)
2993 (yas--mirror-transform field-or-mirror)
2994 (yas--field-transform field-or-mirror)))
2995 (start-point (if (yas--mirror-p field-or-mirror)
2996 (yas--mirror-start field-or-mirror)
2997 (yas--field-start field-or-mirror)))
2998 (transformed (and transform
3000 (goto-char start-point)
3001 (let ((ret (yas--eval-lisp transform)))
3002 (or ret (and empty-on-nil-p "")))))))
3005 (defsubst yas--replace-all (from to &optional text)
3006 "Replace all occurrences from FROM to TO.
3008 With optional string TEXT do it in that string."
3010 (replace-regexp-in-string (regexp-quote from) to text t t)
3011 (goto-char (point-min))
3012 (while (search-forward from nil t)
3013 (replace-match to t t text))))
3015 (defun yas--snippet-find-field (snippet number)
3016 (find-if #'(lambda (field)
3017 (eq number (yas--field-number field)))
3018 (yas--snippet-fields snippet)))
3020 (defun yas--snippet-sort-fields (snippet)
3021 "Sort the fields of SNIPPET in navigation order."
3022 (setf (yas--snippet-fields snippet)
3023 (sort (yas--snippet-fields snippet)
3024 #'yas--snippet-field-compare)))
3026 (defun yas--snippet-field-compare (field1 field2)
3027 "Compare FIELD1 and FIELD2.
3029 The field with a number is sorted first. If they both have a
3030 number, compare through the number. If neither have, compare
3031 through the field's start point"
3032 (let ((n1 (yas--field-number field1))
3033 (n2 (yas--field-number field2)))
3036 (or (zerop n2) (and (not (zerop n1))
3041 (< (yas--field-start field1)
3042 (yas--field-start field2))))))
3044 (defun yas--field-probably-deleted-p (snippet field)
3045 "Guess if SNIPPET's FIELD should be skipped."
3047 ;; field must be zero length
3049 (zerop (- (yas--field-start field) (yas--field-end field)))
3052 ;; 1) is a nested field and it's been modified
3054 (and (yas--field-parent-field field)
3055 (yas--field-modified-p field))
3056 ;; 2) ends just before the snippet end
3058 (and (eq field (car (last (yas--snippet-fields snippet))))
3059 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3060 ;; the field numbered 0, just before the exit marker, should
3063 (not (zerop (yas--field-number field)))))
3065 (defun yas--snippets-at-point (&optional all-snippets)
3066 "Return a sorted list of snippets at point.
3068 The most recently-inserted snippets are returned first."
3070 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3071 (overlay-get ov 'yas--snippet))
3073 (overlays-in (point-min) (point-max))
3074 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3076 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3078 (defun yas-next-field-or-maybe-expand ()
3079 "Try to expand a snippet at a key before point.
3081 Otherwise delegate to `yas-next-field'."
3083 (if yas-triggers-in-field
3084 (let ((yas-fallback-behavior 'return-nil)
3085 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3087 (unless (yas-expand-from-trigger-key active-field)
3091 (defun yas-next-field (&optional arg)
3092 "Navigate to the ARGth next field.
3094 If there's none, exit the snippet."
3098 (snippet (first (yas--snippets-at-point)))
3099 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3100 (live-fields (remove-if #'(lambda (field)
3101 (and (not (eq field active-field))
3102 (yas--field-probably-deleted-p snippet field)))
3103 (yas--snippet-fields snippet)))
3104 (active-field-pos (position active-field live-fields))
3105 (target-pos (and active-field-pos (+ arg active-field-pos)))
3106 (target-field (and target-pos (nth target-pos live-fields))))
3107 ;; First check if we're moving out of a field with a transform
3109 (when (and active-field
3110 (yas--field-transform active-field))
3111 (let* ((yas-moving-away-p t)
3112 (yas-text (yas--field-text-for-display active-field))
3114 (yas-modified-p (yas--field-modified-p active-field)))
3115 ;; primary field transform: exit call to field-transform
3116 (yas--eval-lisp (yas--field-transform active-field))))
3117 ;; Now actually move...
3118 (cond ((and target-pos (>= target-pos (length live-fields)))
3119 (yas-exit-snippet snippet))
3121 (yas--move-to-field snippet target-field))
3125 (defun yas--place-overlays (snippet field)
3126 "Correctly place overlays for SNIPPET's FIELD."
3127 (yas--make-move-field-protection-overlays snippet field)
3128 (yas--make-move-active-field-overlay snippet field))
3130 (defun yas--move-to-field (snippet field)
3131 "Update SNIPPET to move to field FIELD.
3133 Also create some protection overlays"
3134 (goto-char (yas--field-start field))
3135 (yas--place-overlays snippet field)
3136 (overlay-put yas--active-field-overlay 'yas--field field)
3137 (let ((number (yas--field-number field)))
3138 ;; check for the special ${0: ...} field
3139 (if (and number (zerop number))
3141 (set-mark (yas--field-end field))
3142 (setf (yas--snippet-force-exit snippet)
3143 (or (yas--field-transform field)
3145 ;; make this field active
3146 (setf (yas--snippet-active-field snippet) field)
3147 ;; primary field transform: first call to snippet transform
3148 (unless (yas--field-modified-p field)
3149 (if (yas--field-update-display field snippet)
3150 (yas--update-mirrors snippet)
3151 (setf (yas--field-modified-p field) nil))))))
3153 (defun yas-prev-field ()
3154 "Navigate to prev field. If there's none, exit the snippet."
3156 (yas-next-field -1))
3158 (defun yas-abort-snippet (&optional snippet)
3160 (let ((snippet (or snippet
3161 (car (yas--snippets-at-point)))))
3163 (setf (yas--snippet-force-exit snippet) t))))
3165 (defun yas-exit-snippet (snippet)
3166 "Goto exit-marker of SNIPPET."
3167 (interactive (list (first (yas--snippets-at-point))))
3169 (setf (yas--snippet-force-exit snippet) t)
3170 (goto-char (if (yas--snippet-exit snippet)
3171 (yas--exit-marker (yas--snippet-exit snippet))
3172 (overlay-end (yas--snippet-control-overlay snippet))))))
3174 (defun yas-exit-all-snippets ()
3175 "Exit all snippets."
3177 (mapc #'(lambda (snippet)
3178 (yas-exit-snippet snippet)
3179 (yas--check-commit-snippet))
3180 (yas--snippets-at-point 'all-snippets)))
3183 ;;; Some low level snippet-routines:
3185 (defmacro yas--inhibit-overlay-hooks (&rest body)
3186 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3187 (declare (indent 0))
3188 `(let ((yas--inhibit-overlay-hooks t))
3191 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3192 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3194 (defun yas--commit-snippet (snippet)
3195 "Commit SNIPPET, but leave point as it is.
3197 This renders the snippet as ordinary text."
3199 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3201 ;; Save the end of the moribund snippet in case we need to revive it
3202 ;; its original expansion.
3204 (when (and control-overlay
3205 (overlay-buffer control-overlay))
3206 (setq yas-snippet-beg (overlay-start control-overlay))
3207 (setq yas-snippet-end (overlay-end control-overlay))
3208 (delete-overlay control-overlay))
3210 (yas--inhibit-overlay-hooks
3211 (when yas--active-field-overlay
3212 (delete-overlay yas--active-field-overlay))
3213 (when yas--field-protection-overlays
3214 (mapc #'delete-overlay yas--field-protection-overlays)))
3216 ;; stacked expansion: if the original expansion took place from a
3217 ;; field, make sure we advance it here at least to
3218 ;; `yas-snippet-end'...
3220 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3221 (when (and yas-snippet-end previous-field)
3222 (yas--advance-end-maybe previous-field yas-snippet-end)))
3224 ;; Convert all markers to points,
3226 (yas--markers-to-points snippet)
3228 ;; Take care of snippet revival
3230 (if yas-snippet-revival
3231 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3233 ;; Dismember the snippet... this is useful if we get called
3234 ;; again from `yas--take-care-of-redo'....
3235 (setf (yas--snippet-fields snippet) nil)))
3237 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3239 (defun yas--safely-run-hooks (hook-var)
3240 (condition-case error
3241 (run-hooks hook-var)
3243 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3246 (defun yas--check-commit-snippet ()
3247 "Checks if point exited the currently active field of the snippet.
3249 If so cleans up the whole snippet up."
3250 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3251 (snippets-left snippets)
3252 (snippet-exit-transform))
3253 (dolist (snippet snippets)
3254 (let ((active-field (yas--snippet-active-field snippet)))
3255 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3256 (cond ((or snippet-exit-transform
3257 (not (and active-field (yas--field-contains-point-p active-field))))
3258 (setq snippets-left (delete snippet snippets-left))
3259 (setf (yas--snippet-force-exit snippet) nil)
3260 (yas--commit-snippet snippet))
3262 (or (not yas--active-field-overlay)
3263 (not (overlay-buffer yas--active-field-overlay))))
3265 ;; stacked expansion: this case is mainly for recent
3266 ;; snippet exits that place us back int the field of
3270 (yas--move-to-field snippet active-field)
3271 (yas--update-mirrors snippet)))
3274 (unless (or (null snippets) snippets-left)
3275 (if snippet-exit-transform
3276 (yas--eval-lisp-no-saves snippet-exit-transform))
3277 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3279 ;; Apropos markers-to-points:
3281 ;; This was found useful for performance reasons, so that an
3282 ;; excessive number of live markers aren't kept around in the
3283 ;; `buffer-undo-list'. However, in `markers-to-points', the
3284 ;; set-to-nil markers can't simply be discarded and replaced with
3285 ;; fresh ones in `points-to-markers'. The original marker that was
3286 ;; just set to nil has to be reused.
3288 ;; This shouldn't bring horrible problems with undo/redo, but it
3291 (defun yas--markers-to-points (snippet)
3292 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3293 where POINT is the original position of the marker and MARKER is
3294 the original marker object with the position set to nil."
3295 (dolist (field (yas--snippet-fields snippet))
3296 (let ((start (marker-position (yas--field-start field)))
3297 (end (marker-position (yas--field-end field))))
3298 (set-marker (yas--field-start field) nil)
3299 (set-marker (yas--field-end field) nil)
3300 (setf (yas--field-start field) (cons start (yas--field-start field)))
3301 (setf (yas--field-end field) (cons end (yas--field-end field))))
3302 (dolist (mirror (yas--field-mirrors field))
3303 (let ((start (marker-position (yas--mirror-start mirror)))
3304 (end (marker-position (yas--mirror-end mirror))))
3305 (set-marker (yas--mirror-start mirror) nil)
3306 (set-marker (yas--mirror-end mirror) nil)
3307 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3308 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3309 (let ((snippet-exit (yas--snippet-exit snippet)))
3311 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3312 (set-marker (yas--exit-marker snippet-exit) nil)
3313 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3315 (defun yas--points-to-markers (snippet)
3316 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3318 This is done by setting MARKER to POINT with `set-marker'."
3319 (dolist (field (yas--snippet-fields snippet))
3320 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3321 (car (yas--field-start field))))
3322 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3323 (car (yas--field-end field))))
3324 (dolist (mirror (yas--field-mirrors field))
3325 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3326 (car (yas--mirror-start mirror))))
3327 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3328 (car (yas--mirror-end mirror))))))
3329 (let ((snippet-exit (yas--snippet-exit snippet)))
3331 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3332 (car (yas--exit-marker snippet-exit)))))))
3334 (defun yas--field-contains-point-p (field &optional point)
3335 (let ((point (or point
3337 (and (>= point (yas--field-start field))
3338 (<= point (yas--field-end field)))))
3340 (defun yas--field-text-for-display (field)
3341 "Return the propertized display text for field FIELD."
3342 (buffer-substring (yas--field-start field) (yas--field-end field)))
3344 (defun yas--undo-in-progress ()
3345 "True if some kind of undo is in progress."
3346 (or undo-in-progress
3347 (eq this-command 'undo)
3348 (eq this-command 'redo)))
3350 (defun yas--make-control-overlay (snippet start end)
3351 "Creates the control overlay that surrounds the snippet and
3353 (let ((overlay (make-overlay start
3358 (overlay-put overlay 'keymap yas-keymap)
3359 (overlay-put overlay 'priority 100)
3360 (overlay-put overlay 'yas--snippet snippet)
3363 (defun yas-skip-and-clear-or-delete-char (&optional field)
3364 "Clears unmodified field if at field start, skips to next tab.
3366 Otherwise deletes a character normally by calling `delete-char'."
3368 (let ((field (or field
3369 (and yas--active-field-overlay
3370 (overlay-buffer yas--active-field-overlay)
3371 (overlay-get yas--active-field-overlay 'yas--field)))))
3373 (not (yas--field-modified-p field))
3374 (eq (point) (marker-position (yas--field-start field))))
3375 (yas--skip-and-clear field)
3378 (call-interactively 'delete-char)))))
3380 (defun yas--skip-and-clear (field)
3381 "Deletes the region of FIELD and sets it's modified state to t."
3382 ;; Just before skipping-and-clearing the field, mark its children
3383 ;; fields as modified, too. If the children have mirrors-in-fields
3384 ;; this prevents them from updating erroneously (we're skipping and
3387 (yas--mark-this-and-children-modified field)
3388 (delete-region (yas--field-start field) (yas--field-end field)))
3390 (defun yas--mark-this-and-children-modified (field)
3391 (setf (yas--field-modified-p field) t)
3392 (let ((fom (yas--field-next field)))
3394 (yas--fom-parent-field fom))
3395 (when (and (eq (yas--fom-parent-field fom) field)
3397 (yas--mark-this-and-children-modified fom))
3398 (setq fom (yas--fom-next fom)))))
3400 (defun yas--make-move-active-field-overlay (snippet field)
3401 "Place the active field overlay in SNIPPET's FIELD.
3403 Move the overlay, or create it if it does not exit."
3404 (if (and yas--active-field-overlay
3405 (overlay-buffer yas--active-field-overlay))
3406 (move-overlay yas--active-field-overlay
3407 (yas--field-start field)
3408 (yas--field-end field))
3409 (setq yas--active-field-overlay
3410 (make-overlay (yas--field-start field)
3411 (yas--field-end field)
3413 (overlay-put yas--active-field-overlay 'priority 100)
3414 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3415 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3416 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3417 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3418 '(yas--on-field-overlay-modification))
3419 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3420 '(yas--on-field-overlay-modification))))
3422 (defvar yas--inhibit-overlay-hooks nil
3423 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3425 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3426 "Clears the field and updates mirrors, conditionally.
3428 Only clears the field if it hasn't been modified and it point it
3429 at field start. This hook doesn't do anything if an undo is in
3431 (unless (or yas--inhibit-overlay-hooks
3432 (yas--undo-in-progress))
3433 (let* ((field (overlay-get overlay 'yas--field))
3434 (number (and field (yas--field-number field)))
3435 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3437 (yas--advance-end-maybe field (overlay-end overlay))
3439 (yas--field-update-display field snippet))
3440 (yas--update-mirrors snippet))
3442 (when (and (not after?)
3443 (not (yas--field-modified-p field))
3444 (eq (point) (if (markerp (yas--field-start field))
3445 (marker-position (yas--field-start field))
3446 (yas--field-start field))))
3447 (yas--skip-and-clear field))
3448 (setf (yas--field-modified-p field) t))))))
3450 ;;; Apropos protection overlays:
3452 ;; These exist for nasty users who will try to delete parts of the
3453 ;; snippet outside the active field. Actual protection happens in
3454 ;; `yas--on-protection-overlay-modification'.
3456 ;; Currently this signals an error which inhibits the command. For
3457 ;; commands that move point (like `kill-line'), point is restored in
3458 ;; the `yas--post-command-handler' using a global
3459 ;; `yas--protection-violation' variable.
3461 ;; Alternatively, I've experimented with an implementation that
3462 ;; commits the snippet before actually calling `this-command'
3463 ;; interactively, and then signals an error, which is ignored. but
3464 ;; blocks all other million modification hooks. This presented some
3465 ;; problems with stacked expansion.
3467 (defun yas--make-move-field-protection-overlays (snippet field)
3468 "Place protection overlays surrounding SNIPPET's FIELD.
3470 Move the overlays, or create them if they do not exit."
3471 (let ((start (yas--field-start field))
3472 (end (yas--field-end field)))
3473 ;; First check if the (1+ end) is contained in the buffer,
3474 ;; otherwise we'll have to do a bit of cheating and silently
3475 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3476 ;; when using stacked expansion
3478 (when (< (buffer-size) end)
3480 (yas--inhibit-overlay-hooks
3481 (goto-char (point-max))
3483 ;; go on to normal overlay creation/moving
3485 (cond ((and yas--field-protection-overlays
3486 (every #'overlay-buffer yas--field-protection-overlays))
3487 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3488 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3490 (setq yas--field-protection-overlays
3491 (list (make-overlay (1- start) start nil t nil)
3492 (make-overlay end (1+ end) nil t nil)))
3493 (dolist (ov yas--field-protection-overlays)
3494 (overlay-put ov 'face 'yas--field-debug-face)
3495 (overlay-put ov 'yas--snippet snippet)
3496 ;; (overlay-put ov 'evaporate t)
3497 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3499 (defvar yas--protection-violation nil
3500 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3502 Functions in the `post-command-hook', for example
3503 `yas--post-command-handler' can check it and reset its value to
3504 nil. The variables value is the point where the violation
3507 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3508 "Signals a snippet violation, then issues error.
3510 The error should be ignored in `debug-ignored-errors'"
3511 (unless yas--inhibit-overlay-hooks
3512 (cond ((not (or after?
3513 (yas--undo-in-progress)))
3514 (setq yas--protection-violation (point))
3515 (error "Exit the snippet first!")))))
3517 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3520 ;;; Snippet expansion and "stacked" expansion:
3522 ;; Stacked expansion is when you try to expand a snippet when already
3523 ;; inside a snippet expansion.
3525 ;; The parent snippet does not run its fields modification hooks
3526 ;; (`yas--on-field-overlay-modification' and
3527 ;; `yas--on-protection-overlay-modification') while the child snippet
3528 ;; is active. This means, among other things, that the mirrors of the
3529 ;; parent snippet are not updated, this only happening when one exits
3530 ;; the child snippet.
3532 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3533 ;; bits of code in `yas-expand-snippet' and
3534 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3537 ;; This was thought to be safer in an undo/redo perspective, but
3538 ;; maybe the correct implementation is to make the globals
3539 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3540 ;; snippet-local and be active even while the child snippet is
3541 ;; running. This would mean a lot of overlay modification hooks
3542 ;; running, but if managed correctly (including overlay priorities)
3543 ;; they should account for all situations...
3545 (defun yas-expand-snippet (content &optional start end expand-env)
3546 "Expand snippet CONTENT at current point.
3548 Text between START and END will be deleted before inserting
3549 template. EXPAND-ENV is are let-style variable to value bindings
3550 considered when expanding the snippet."
3551 (run-hooks 'yas-before-expand-snippet-hook)
3554 (let* ((yas-selected-text (or yas-selected-text
3555 (and (region-active-p)
3556 (buffer-substring-no-properties (region-beginning)
3559 (and (region-active-p)
3563 (and (region-active-p)
3566 (to-delete (and start
3568 (buffer-substring-no-properties start end)))
3571 (setq yas--indent-original-column (current-column))
3572 ;; Delete the region to delete, this *does* get undo-recorded.
3574 (when (and to-delete
3576 (delete-region start end))
3578 (cond ((listp content)
3579 ;; x) This is a snippet-command
3581 (yas--eval-lisp-no-saves content))
3583 ;; x) This is a snippet-snippet :-)
3585 ;; Narrow the region down to the content, shoosh the
3586 ;; `buffer-undo-list', and create the snippet, the new
3587 ;; snippet updates its mirrors once, so we are left with
3588 ;; some plain text. The undo action for deleting this
3589 ;; plain text will get recorded at the end.
3591 ;; stacked expansion: also shoosh the overlay modification hooks
3593 (narrow-to-region start start)
3594 (let ((buffer-undo-list t))
3595 ;; snippet creation might evaluate users elisp, which
3596 ;; might generate errors, so we have to be ready to catch
3597 ;; them mostly to make the undo information
3599 (setq yas--start-column (save-restriction (widen) (current-column)))
3600 (yas--inhibit-overlay-hooks
3603 (eval `(let* ,expand-env
3605 (yas--snippet-create (point-min) (point-max))))
3607 (yas--snippet-create (point-min) (point-max)))))))
3609 ;; stacked-expansion: This checks for stacked expansion, save the
3610 ;; `yas--previous-active-field' and advance its boundary.
3612 (let ((existing-field (and yas--active-field-overlay
3613 (overlay-buffer yas--active-field-overlay)
3614 (overlay-get yas--active-field-overlay 'yas--field))))
3615 (when existing-field
3616 (setf (yas--snippet-previous-active-field snippet) existing-field)
3617 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3619 ;; Exit the snippet immediately if no fields
3621 (unless (yas--snippet-fields snippet)
3622 (yas-exit-snippet snippet))
3624 ;; Push two undo actions: the deletion of the inserted contents of
3625 ;; the new snippet (without the "key") followed by an apply of
3626 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3628 ;; A small exception, if `yas-also-auto-indent-first-line'
3629 ;; is t and `yas--indent' decides to indent the line to a
3630 ;; point before the actual expansion point, undo would be
3631 ;; messed up. We call the early point "newstart"". case,
3632 ;; and attempt to fix undo.
3634 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3635 (end (overlay-end (yas--snippet-control-overlay snippet))))
3636 (when (< newstart start)
3637 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3638 (push (cons newstart end) buffer-undo-list)
3639 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3641 ;; Now, schedule a move to the first field
3643 (let ((first-field (car (yas--snippet-fields snippet))))
3645 (sit-for 0) ;; fix issue 125
3646 (yas--move-to-field snippet first-field)))
3647 (yas--message 3 "snippet expanded.")
3650 (defun yas--take-care-of-redo (beg end snippet)
3651 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3653 Meant to exit in the `buffer-undo-list'."
3654 ;; slightly optimize: this action is only needed for snippets with
3655 ;; at least one field
3656 (when (yas--snippet-fields snippet)
3657 (yas--commit-snippet snippet)))
3659 (defun yas--snippet-revive (beg end snippet)
3660 "Revives SNIPPET and creates a control overlay from BEG to END.
3662 BEG and END are, we hope, the original snippets boundaries. All
3663 the markers/points exiting existing inside SNIPPET should point
3664 to their correct locations *at the time the snippet is revived*.
3666 After revival, push the `yas--take-care-of-redo' in the
3668 ;; Reconvert all the points to markers
3670 (yas--points-to-markers snippet)
3671 ;; When at least one editable field existed in the zombie snippet,
3672 ;; try to revive the whole thing...
3674 (let ((target-field (or (yas--snippet-active-field snippet)
3675 (car (yas--snippet-fields snippet)))))
3677 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3678 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3680 (yas--move-to-field snippet target-field)
3682 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3683 buffer-undo-list))))
3685 (defun yas--snippet-create (begin end)
3686 "Creates a snippet from an template inserted between BEGIN and END.
3688 Returns the newly created snippet."
3689 (let ((snippet (yas--make-snippet)))
3691 (yas--snippet-parse-create snippet)
3693 ;; Sort and link each field
3694 (yas--snippet-sort-fields snippet)
3696 ;; Create keymap overlay for snippet
3697 (setf (yas--snippet-control-overlay snippet)
3698 (yas--make-control-overlay snippet (point-min) (point-max)))
3701 (goto-char (point-max))
3706 ;;; Apropos adjacencies and "fom's":
3708 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3709 ;; recently expanded snippet, we might actually have many fields,
3710 ;; mirrors (and the snippet exit) in the very same position in the
3711 ;; buffer. Therefore we need to single-link the
3712 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3713 ;; according to their original positions in the buffer.
3715 ;; Then we have operation `yas--advance-end-maybe' and
3716 ;; `yas--advance-start-maybe', which conditionally push the starts and
3717 ;; ends of these foms down the chain.
3719 ;; This allows for like the printf with the magic ",":
3721 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3722 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3724 (defun yas--fom-start (fom)
3725 (cond ((yas--field-p fom)
3726 (yas--field-start fom))
3727 ((yas--mirror-p fom)
3728 (yas--mirror-start fom))
3730 (yas--exit-marker fom))))
3732 (defun yas--fom-end (fom)
3733 (cond ((yas--field-p fom)
3734 (yas--field-end fom))
3735 ((yas--mirror-p fom)
3736 (yas--mirror-end fom))
3738 (yas--exit-marker fom))))
3740 (defun yas--fom-next (fom)
3741 (cond ((yas--field-p fom)
3742 (yas--field-next fom))
3743 ((yas--mirror-p fom)
3744 (yas--mirror-next fom))
3746 (yas--exit-next fom))))
3748 (defun yas--fom-parent-field (fom)
3749 (cond ((yas--field-p fom)
3750 (yas--field-parent-field fom))
3751 ((yas--mirror-p fom)
3752 (yas--mirror-parent-field fom))
3756 (defun yas--calculate-adjacencies (snippet)
3757 "Calculate adjacencies for fields or mirrors of SNIPPET.
3759 This is according to their relative positions in the buffer, and
3760 has to be called before the $-constructs are deleted."
3761 (labels ((yas--fom-set-next-fom (fom nextfom)
3762 (cond ((yas--field-p fom)
3763 (setf (yas--field-next fom) nextfom))
3764 ((yas--mirror-p fom)
3765 (setf (yas--mirror-next fom) nextfom))
3767 (setf (yas--exit-next fom) nextfom))))
3768 (yas--compare-fom-begs (fom1 fom2)
3769 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3770 (yas--mirror-p fom2)
3771 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3772 (yas--link-foms (fom1 fom2)
3773 (yas--fom-set-next-fom fom1 fom2)))
3774 ;; make some yas--field, yas--mirror and yas--exit soup
3776 (when (yas--snippet-exit snippet)
3777 (push (yas--snippet-exit snippet) soup))
3778 (dolist (field (yas--snippet-fields snippet))
3780 (dolist (mirror (yas--field-mirrors field))
3781 (push mirror soup)))
3784 #'yas--compare-fom-begs))
3786 (reduce #'yas--link-foms soup)))))
3788 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3789 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3791 Use the tightest containing field if more than one field contains
3792 the mirror. Intended to be called *before* the dollar-regions are
3794 (let ((min (point-min))
3796 (dolist (field (yas--snippet-fields snippet))
3797 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3798 (<= (yas--mirror-end mirror) (yas--field-end field))
3799 (< min (yas--field-start field))
3800 (< (yas--field-end field) max))
3801 (setq min (yas--field-start field)
3802 max (yas--field-end field))
3803 (setf (yas--mirror-parent-field mirror) field)))))
3805 (defun yas--advance-end-maybe (fom newend)
3806 "Maybe advance FOM's end to NEWEND if it needs it.
3810 * call `yas--advance-start-maybe' on FOM's next fom.
3812 * in case FOM is field call `yas--advance-end-maybe' on its parent
3815 Also, if FOM is an exit-marker, always call
3816 `yas--advance-start-maybe' on its next fom. This is because
3817 exit-marker have identical start and end markers."
3818 (cond ((and fom (< (yas--fom-end fom) newend))
3819 (set-marker (yas--fom-end fom) newend)
3820 (yas--advance-start-maybe (yas--fom-next fom) newend)
3821 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3823 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3825 (defun yas--advance-start-maybe (fom newstart)
3826 "Maybe advance FOM's start to NEWSTART if it needs it.
3828 If it does, also call `yas--advance-end-maybe' on FOM."
3829 (when (and fom (< (yas--fom-start fom) newstart))
3830 (set-marker (yas--fom-start fom) newstart)
3831 (yas--advance-end-maybe fom newstart)))
3833 (defun yas--advance-end-of-parents-maybe (field newend)
3834 "Like `yas--advance-end-maybe' but for parent fields.
3836 Only works for fields and doesn't care about the start of the
3837 next FOM. Works its way up recursively for parents of parents."
3839 (< (yas--field-end field) newend))
3840 (set-marker (yas--field-end field) newend)
3841 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3843 (defvar yas--dollar-regions nil
3844 "When expanding the snippet the \"parse-create\" functions add
3845 cons cells to this var.")
3847 (defvar yas--backquote-markers-and-strings nil
3848 "List of (MARKER . STRING) marking where the values from
3849 backquoted lisp expressions should be inserted at the end of
3852 (defun yas--snippet-parse-create (snippet)
3853 "Parse a recently inserted snippet template, creating all
3854 necessary fields, mirrors and exit points.
3856 Meant to be called in a narrowed buffer, does various passes"
3857 (let ((parse-start (point)))
3858 ;; Reset the yas--dollar-regions
3860 (setq yas--dollar-regions nil)
3861 ;; protect just the backquotes
3863 (yas--protect-escapes nil '(?`))
3864 ;; replace all backquoted expressions
3866 (goto-char parse-start)
3867 (yas--save-backquotes)
3868 ;; protect escaped characters
3870 (yas--protect-escapes)
3871 ;; parse fields with {}
3873 (goto-char parse-start)
3874 (yas--field-parse-create snippet)
3875 ;; parse simple mirrors and fields
3877 (goto-char parse-start)
3878 (yas--simple-mirror-parse-create snippet)
3879 ;; parse mirror transforms
3881 (goto-char parse-start)
3882 (yas--transform-mirror-parse-create snippet)
3883 ;; calculate adjacencies of fields and mirrors
3885 (yas--calculate-adjacencies snippet)
3886 ;; Delete $-constructs
3888 (yas--delete-regions yas--dollar-regions)
3889 ;; restore backquoted expression values
3891 (yas--restore-backquotes)
3894 (goto-char parse-start)
3895 (yas--restore-escapes)
3896 ;; update mirrors for the first time
3898 (yas--update-mirrors snippet)
3899 ;; indent the best we can
3901 (goto-char parse-start)
3902 (yas--indent snippet)))
3904 (defun yas--indent-according-to-mode (snippet-markers)
3905 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3906 ;;; Apropos indenting problems....
3908 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3909 ;; is available. Some implementations of these functions delete text
3910 ;; before they insert. If there happens to be a marker just after
3911 ;; the text being deleted, the insertion actually happens after the
3912 ;; marker, which misplaces it.
3914 ;; This would also happen if we had used overlays with the
3915 ;; `front-advance' property set to nil.
3917 ;; This is why I have these `trouble-markers', they are the ones at
3918 ;; they are the ones at the first non-whitespace char at the line
3919 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3920 ;; we should be at the correct to restore them to. All other
3921 ;; non-trouble-markers have been *pushed* and don't need special
3924 (goto-char (yas--real-line-beginning))
3925 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3931 (indent-according-to-mode)
3932 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3934 (mapc #'(lambda (marker)
3935 (set-marker marker (point)))
3938 (defvar yas--indent-original-column nil)
3939 (defun yas--indent (snippet)
3940 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3941 ;; Look for those $>
3943 (while (re-search-forward "$>" nil t)
3944 (delete-region (match-beginning 0) (match-end 0))
3945 (when (not (eq yas-indent-line 'auto))
3946 (yas--indent-according-to-mode snippet-markers))))
3947 ;; Now do stuff for 'fixed and 'auto
3949 (cond ((eq yas-indent-line 'fixed)
3950 (while (and (zerop (forward-line))
3951 (zerop (current-column)))
3952 (indent-to-column yas--indent-original-column)))
3953 ((eq yas-indent-line 'auto)
3954 (let ((end (set-marker (make-marker) (point-max)))
3955 (indent-first-line-p yas-also-auto-indent-first-line))
3956 (while (and (zerop (if indent-first-line-p
3959 (setq indent-first-line-p nil))
3963 (yas--indent-according-to-mode snippet-markers))))
3967 (defun yas--collect-snippet-markers (snippet)
3968 "Make a list of all the markers used by SNIPPET."
3970 (dolist (field (yas--snippet-fields snippet))
3971 (push (yas--field-start field) markers)
3972 (push (yas--field-end field) markers)
3973 (dolist (mirror (yas--field-mirrors field))
3974 (push (yas--mirror-start mirror) markers)
3975 (push (yas--mirror-end mirror) markers)))
3976 (let ((snippet-exit (yas--snippet-exit snippet)))
3977 (when (and snippet-exit
3978 (marker-buffer (yas--exit-marker snippet-exit)))
3979 (push (yas--exit-marker snippet-exit) markers)))
3982 (defun yas--real-line-beginning ()
3983 (let ((c (char-after (line-beginning-position)))
3984 (n (line-beginning-position)))
3985 (while (or (eql c ?\ )
3988 (setq c (char-after n)))
3991 (defun yas--escape-string (escaped)
3992 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3994 (defun yas--protect-escapes (&optional text escaped)
3995 "Protect all escaped characters with their numeric ASCII value.
3997 With optional string TEXT do it in string instead of buffer."
3998 (let ((changed-text text)
3999 (text-provided-p text))
4000 (mapc #'(lambda (escaped)
4002 (yas--replace-all (concat "\\" (char-to-string escaped))
4003 (yas--escape-string escaped)
4004 (when text-provided-p changed-text))))
4005 (or escaped yas--escaped-characters))
4008 (defun yas--restore-escapes (&optional text escaped)
4009 "Restore all escaped characters from their numeric ASCII value.
4011 With optional string TEXT do it in string instead of the buffer."
4012 (let ((changed-text text)
4013 (text-provided-p text))
4014 (mapc #'(lambda (escaped)
4016 (yas--replace-all (yas--escape-string escaped)
4017 (char-to-string escaped)
4018 (when text-provided-p changed-text))))
4019 (or escaped yas--escaped-characters))
4022 (defun yas--save-backquotes ()
4023 "Save all the \"`(lisp-expression)`\"-style expressions
4024 with their evaluated value into `yas--backquote-markers-and-strings'."
4025 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4026 (let ((current-string (match-string-no-properties 1)) transformed)
4027 (delete-region (match-beginning 0) (match-end 0))
4028 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4029 (goto-char (match-beginning 0))
4031 (let ((marker (make-marker)))
4032 (insert "Y") ;; quite horrendous, I love it :)
4033 (set-marker marker (point))
4035 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4037 (defun yas--restore-backquotes ()
4038 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4039 (while yas--backquote-markers-and-strings
4040 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4041 (marker (car marker-and-string))
4042 (string (cdr marker-and-string)))
4048 (set-marker marker nil)))))
4050 (defun yas--scan-sexps (from count)
4052 (with-syntax-table (standard-syntax-table)
4053 (scan-sexps from count))
4057 (defun yas--make-marker (pos)
4058 "Create a marker at POS with nil `marker-insertion-type'."
4059 (let ((marker (set-marker (make-marker) pos)))
4060 (set-marker-insertion-type marker nil)
4063 (defun yas--field-parse-create (snippet &optional parent-field)
4064 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4066 The following count as a field:
4068 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4070 * \"${n: text$(expression)}, the same with a lisp expression;
4071 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4073 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4075 When multiple expressions are found, only the last one counts."
4078 (while (re-search-forward yas--field-regexp nil t)
4079 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4080 (number (and (match-string-no-properties 1)
4081 (string-to-number (match-string-no-properties 1))))
4082 (brand-new-field (and real-match-end-0
4083 ;; break if on "$(" immediately
4084 ;; after the ":", this will be
4085 ;; caught as a mirror with
4087 (not (save-match-data
4088 (eq (string-match "$[ \t\n]*("
4089 (match-string-no-properties 2)) 0)))
4090 ;; allow ${0: some exit text}
4091 ;; (not (and number (zerop number)))
4092 (yas--make-field number
4093 (yas--make-marker (match-beginning 2))
4094 (yas--make-marker (1- real-match-end-0))
4096 (when brand-new-field
4097 (goto-char real-match-end-0)
4098 (push (cons (1- real-match-end-0) real-match-end-0)
4099 yas--dollar-regions)
4100 (push (cons (match-beginning 0) (match-beginning 2))
4101 yas--dollar-regions)
4102 (push brand-new-field (yas--snippet-fields snippet))
4105 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4106 (goto-char (point-min))
4107 (yas--field-parse-create snippet brand-new-field)))))))
4108 ;; if we entered from a parent field, now search for the
4109 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4110 ;; primary field transformations
4114 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4115 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4116 ;; commit the primary field transformation if:
4118 ;; 1. we don't find it in yas--dollar-regions (a subnested
4119 ;; field) might have already caught it.
4121 ;; 2. we really make sure we have either two '$' or some
4122 ;; text and a '$' after the colon ':'. This is a FIXME: work
4123 ;; my regular expressions and end these ugly hacks.
4125 (when (and real-match-end-1
4126 (not (member (cons (match-beginning 0)
4128 yas--dollar-regions))
4130 (char-before (1- (match-beginning 1))))))
4131 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4133 (setf (yas--field-transform parent-field)
4134 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4135 (push (cons (match-beginning 0) real-match-end-1)
4136 yas--dollar-regions)))))))
4138 (defun yas--transform-mirror-parse-create (snippet)
4139 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4140 (while (re-search-forward yas--transform-mirror-regexp nil t)
4141 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4142 (number (string-to-number (match-string-no-properties 1)))
4144 (not (zerop number))
4145 (yas--snippet-find-field snippet number)))
4147 (and real-match-end-0
4149 (yas--make-mirror (yas--make-marker (match-beginning 0))
4150 (yas--make-marker (match-beginning 0))
4152 (yas--restore-escapes
4153 (buffer-substring-no-properties (match-beginning 2)
4154 (1- real-match-end-0))))))))
4155 (when brand-new-mirror
4156 (push brand-new-mirror
4157 (yas--field-mirrors field))
4158 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4159 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4161 (defun yas--simple-mirror-parse-create (snippet)
4162 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4163 (while (re-search-forward yas--simple-mirror-regexp nil t)
4164 (let ((number (string-to-number (match-string-no-properties 1))))
4165 (cond ((zerop number)
4167 (setf (yas--snippet-exit snippet)
4168 (yas--make-exit (yas--make-marker (match-end 0))))
4170 (goto-char (match-beginning 0))
4171 (when yas-wrap-around-region
4172 (cond (yas-selected-text
4173 (insert yas-selected-text))
4174 ((and (eq yas-wrap-around-region 'cua)
4177 (insert (prog1 (get-register ?0)
4178 (set-register ?0 nil))))))
4179 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4180 yas--dollar-regions)))
4182 (let ((field (yas--snippet-find-field snippet number)))
4184 (let ((brand-new-mirror (yas--make-mirror
4185 (yas--make-marker (match-beginning 0))
4186 (yas--make-marker (match-beginning 0))
4188 (push brand-new-mirror
4189 (yas--field-mirrors field))
4190 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4191 (push (yas--make-field number
4192 (yas--make-marker (match-beginning 0))
4193 (yas--make-marker (match-beginning 0))
4195 (yas--snippet-fields snippet))))
4196 (push (cons (match-beginning 0) (match-end 0))
4197 yas--dollar-regions))))))
4199 (defun yas--delete-regions (regions)
4200 "Sort disjuct REGIONS by start point, then delete from the back."
4201 (mapc #'(lambda (reg)
4202 (delete-region (car reg) (cdr reg)))
4205 (>= (car r1) (car r2))))))
4207 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4208 (let* ((parent (yas--mirror-parent-field mirror))
4209 (parents-mirrors (and parent
4210 (yas--field-mirrors parent))))
4211 (or (yas--mirror-depth mirror)
4212 (setf (yas--mirror-depth mirror)
4213 (cond ((memq mirror traversed)
4215 ((and parent parents-mirrors)
4217 (mapcar #'(lambda (m)
4218 (yas--calculate-mirror-depth m
4227 (defun yas--update-mirrors (snippet)
4228 "Updates all the mirrors of SNIPPET."
4230 (dolist (field-and-mirror (sort
4231 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4232 ;; where F is the field that M is mirroring
4234 (mapcan #'(lambda (field)
4235 (mapcar #'(lambda (mirror)
4236 (cons field mirror))
4237 (yas--field-mirrors field)))
4238 (yas--snippet-fields snippet))
4239 ;; then sort this list so that entries with mirrors with parent
4240 ;; fields appear before. This was important for fixing #290, and
4241 ;; luckily also handles the case where a mirror in a field causes
4242 ;; another mirror to need reupdating
4244 #'(lambda (field-and-mirror1 field-and-mirror2)
4245 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4246 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4247 (let* ((field (car field-and-mirror))
4248 (mirror (cdr field-and-mirror))
4249 (parent-field (yas--mirror-parent-field mirror)))
4250 ;; before updating a mirror with a parent-field, maybe advance
4254 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4255 ;; update this mirror
4257 (yas--mirror-update-display mirror field)
4258 ;; `yas--place-overlays' is needed if the active field and
4259 ;; protected overlays have been changed because of insertions
4260 ;; in `yas--mirror-update-display'
4262 (when (eq field (yas--snippet-active-field snippet))
4263 (yas--place-overlays snippet field))))))
4265 (defun yas--mirror-update-display (mirror field)
4266 "Update MIRROR according to FIELD (and mirror transform)."
4268 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4269 (reflection (and (not (and mirror-parent-field
4270 (yas--field-modified-p mirror-parent-field)))
4271 (or (yas--apply-transform mirror field 'empty-on-nil)
4272 (yas--field-text-for-display field)))))
4273 (when (and reflection
4274 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4275 (yas--mirror-end mirror)))))
4276 (goto-char (yas--mirror-start mirror))
4277 (yas--inhibit-overlay-hooks
4278 (insert reflection))
4279 (if (> (yas--mirror-end mirror) (point))
4280 (delete-region (point) (yas--mirror-end mirror))
4281 (set-marker (yas--mirror-end mirror) (point))
4282 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4283 ;; super-special advance
4284 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4286 (defun yas--field-update-display (field snippet)
4287 "Much like `yas--mirror-update-display', but for fields."
4288 (when (yas--field-transform field)
4289 (let ((transformed (and (not (eq (yas--field-number field) 0))
4290 (yas--apply-transform field field)))
4292 (when (and transformed
4293 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4294 (yas--field-end field)))))
4295 (setf (yas--field-modified-p field) t)
4296 (goto-char (yas--field-start field))
4297 (yas--inhibit-overlay-hooks
4298 (insert transformed)
4299 (if (> (yas--field-end field) (point))
4300 (delete-region (point) (yas--field-end field))
4301 (set-marker (yas--field-end field) (point))
4302 (yas--advance-start-maybe (yas--field-next field) (point)))
4306 ;;; Post-command hook:
4308 (defun yas--post-command-handler ()
4309 "Handles various yasnippet conditions after each command."
4310 (cond (yas--protection-violation
4311 (goto-char yas--protection-violation)
4312 (setq yas--protection-violation nil))
4313 ((eq 'undo this-command)
4315 ;; After undo revival the correct field is sometimes not
4316 ;; restored correctly, this condition handles that
4318 (let* ((snippet (car (yas--snippets-at-point)))
4319 (target-field (and snippet
4320 (find-if-not #'(lambda (field)
4321 (yas--field-probably-deleted-p snippet field))
4323 (cons (yas--snippet-active-field snippet)
4324 (yas--snippet-fields snippet)))))))
4326 (yas--move-to-field snippet target-field))))
4327 ((not (yas--undo-in-progress))
4328 ;; When not in an undo, check if we must commit the snippet
4329 ;; (user exited it).
4330 (yas--check-commit-snippet))))
4334 ;; The docstrings for some functions are generated dynamically
4335 ;; depending on the context.
4337 (put 'yas-expand 'function-documentation
4338 '(yas--expand-from-trigger-key-doc))
4339 (defun yas--expand-from-trigger-key-doc ()
4340 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4341 (let ((fallback-description
4342 (cond ((eq yas-fallback-behavior 'call-other-command)
4343 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4345 (format " call command `%s'." (pp-to-string fallback)))
4346 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4347 ((eq yas-fallback-behavior 'return-nil)
4350 ", defer to `yas-fallback-behaviour' (which see)"))))
4351 (concat "Expand a snippet before point. If no snippet
4352 expansion is possible,"
4353 fallback-description
4354 "\n\nOptional argument FIELD is for non-interactive use and is an
4355 object satisfying `yas--field-p' to restrict the expansion to.")))
4357 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4358 (defun yas--expand-from-keymap-doc ()
4359 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4360 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4361 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4362 (when (eq this-command 'describe-key)
4363 (let* ((vec (this-single-command-keys))
4364 (templates (mapcan #'(lambda (table)
4365 (yas--fetch table vec))
4366 (yas--get-snippet-tables)))
4367 (yas--direct-keymaps nil)
4368 (fallback (key-binding vec)))
4369 (concat "In this case, "
4371 (concat "these snippets are bound to this key:\n"
4372 (yas--template-pretty-list templates)
4373 "\n\nIf none of these expands, "))
4375 (format "fallback `%s' will be called." (pp-to-string fallback)))
4376 "no fallback keybinding is called."))))))
4378 (defun yas--template-pretty-list (templates)
4380 (yas-buffer-local-condition 'always))
4381 (dolist (plate templates)
4382 (setq acc (concat acc "\n*) "
4383 (propertize (concat "\\\\snippet `" (car plate) "'")
4384 'yasnippet (cdr plate)))))
4387 (define-button-type 'help-snippet-def
4388 :supertype 'help-xref
4389 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4390 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4392 (defun yas--snippet-description-finish-runonce ()
4393 "Final adjustments for the help buffer when snippets are concerned."
4394 (yas--create-snippet-xrefs)
4395 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4397 (defun yas--create-snippet-xrefs ()
4399 (goto-char (point-min))
4400 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4401 (let ((template (get-text-property (match-beginning 1)
4404 (help-xref-button 1 'help-snippet-def template)
4405 (kill-region (match-end 1) (match-end 0))
4406 (kill-region (match-beginning 0) (match-beginning 1)))))))
4408 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4409 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4411 Remaining args as in `yas-expand-snippet'."
4412 (let* ((table (gethash mode-symbol yas--tables))
4413 (yas--current-template (and table
4414 (gethash uuid (yas--table-uuidhash table)))))
4415 (when yas--current-template
4416 (yas-expand-snippet (yas--template-content yas--current-template)))))
4420 (defvar yas-verbosity 4
4421 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4423 (defun yas--message (level message &rest args)
4424 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4425 (when (> yas-verbosity level)
4426 (message "%s" (apply #'yas--format message args))))
4428 (defun yas--format (format-control &rest format-args)
4429 (apply #'format (concat "[yas] " format-control) format-args))
4436 ;; `locate-dominating-file'
4437 ;; `region-active-p'
4439 ;; added for compatibility in emacsen < 23
4440 (unless (>= emacs-major-version 23)
4441 (unless (fboundp 'region-active-p)
4442 (defun region-active-p () (and transient-mark-mode mark-active)))
4444 (unless (fboundp 'locate-dominating-file)
4445 (defvar locate-dominating-stop-dir-regexp
4446 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4447 "Regexp of directory names which stop the search in `locate-dominating-file'.
4448 Any directory whose name matches this regexp will be treated like
4449 a kind of root directory by `locate-dominating-file' which will stop its search
4450 when it bumps into it.
4451 The default regexp prevents fruitless and time-consuming attempts to find
4452 special files in directories in which filenames are interpreted as hostnames,
4453 or mount points potentially requiring authentication as a different user.")
4455 (defun locate-dominating-file (file name)
4456 "Look up the directory hierarchy from FILE for a file named NAME.
4457 Stop at the first parent directory containing a file NAME,
4458 and return the directory. Return nil if not found."
4459 ;; We used to use the above locate-dominating-files code, but the
4460 ;; directory-files call is very costly, so we're much better off doing
4461 ;; multiple calls using the code in here.
4463 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4464 ;; `name' in /home or in /.
4465 (setq file (abbreviate-file-name file))
4468 ;; `user' is not initialized outside the loop because
4469 ;; `file' may not exist, so we may have to walk up part of the
4470 ;; hierarchy before we find the "initial UUID".
4473 (while (not (or root
4475 ;; FIXME: Disabled this heuristic because it is sometimes
4477 ;; As a heuristic, we stop looking up the hierarchy of
4478 ;; directories as soon as we find a directory belonging
4479 ;; to another user. This should save us from looking in
4480 ;; things like /net and /afs. This assumes that all the
4481 ;; files inside a project belong to the same user.
4482 ;; (let ((prev-user user))
4483 ;; (setq user (nth 2 (file-attributes file)))
4484 ;; (and prev-user (not (equal user prev-user))))
4485 (string-match locate-dominating-stop-dir-regexp file)))
4486 (setq try (file-exists-p (expand-file-name name file)))
4487 (cond (try (setq root file))
4488 ((equal file (setq prev-file file
4489 file (file-name-directory
4490 (directory-file-name file))))
4494 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4495 ;; (when it execute forward-char) and interrupt the after change
4496 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4497 ;; invoked. Here's a way to reproduce it:
4499 ;; # open a *new* Emacs.
4500 ;; # load yasnippet.
4501 ;; # open a *new* .cpp file.
4502 ;; # input "inc" and press TAB to expand the snippet.
4503 ;; # select the `#include <...>` snippet.
4504 ;; # type inside `<>`
4506 (defadvice c-neutralize-syntax-in-CPP
4507 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4508 "Adviced `c-neutralize-syntax-in-CPP' to properly
4509 handle the end-of-buffer error fired in it by calling
4510 `forward-char' at the end of buffer."
4513 (error (message (error-message-string err)))))
4515 ;; disable c-electric-* serial command in YAS fields
4516 (add-hook 'c-mode-common-hook
4518 (dolist (k '(":" ">" ";" "<" "{" "}"))
4519 (define-key (symbol-value (make-local-variable 'yas-keymap))
4520 k 'self-insert-command))))
4522 ;;; Backward compatibility to yasnippet <= 0.7
4524 (defvar yas--exported-syms '(;; `defcustom's
4527 yas-prompt-functions
4529 yas-also-auto-indent-first-line
4531 yas-triggers-in-field
4532 yas-fallback-behavior
4533 yas-choose-keys-first
4534 yas-choose-tables-first
4537 yas-wrap-around-region
4540 yas-expand-only-for-last-commands
4541 yas-field-highlight-face
4543 ;; these vars can be customized as well
4549 yas-after-exit-snippet-hook
4550 yas-before-expand-snippet-hook
4551 yas-buffer-local-condition
4554 ;; prompting functions
4559 yas-completing-prompt
4562 ;; interactive functions
4567 yas-direct-keymaps-reload
4571 yas-compile-directory
4574 yas-expand-from-trigger-key
4575 yas-expand-from-keymap
4577 yas-visit-snippet-file
4579 yas-load-snippet-buffer
4582 yas-next-field-or-maybe-expand
4587 yas-exit-all-snippets
4588 yas-skip-and-clear-or-delete-char
4590 ;; symbols that I "exported" for use
4591 ;; in snippets and hookage
4609 yas-default-from-field
4612 yas-define-condition-cache
4613 yas-hippie-try-expand
4616 ;; debug definitions
4617 ;; yas-debug-snippet-vars
4618 ;; yas-exterminate-package
4621 ;; testing definitions
4622 ;; yas-should-expand
4623 ;; yas-should-not-expand
4625 ;; yas-make-file-or-dirs
4627 ;; yas-saving-variables
4628 ;; yas-call-with-snippet-dirs
4629 ;; yas-with-snippet-dirs
4631 "Exported yasnippet symbols.
4633 i.e. ones that I will try to keep in future yasnippet versions
4634 and ones that other elisp libraries can more or less safely rely
4637 (defvar yas--dont-backport '(yas-active-keys)
4638 "Exported symbols that don't map back to \"yas/*\" variants.")
4640 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4641 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4643 (make-obsolete-variable backported sym "yasnippet 0.8")
4644 (defvaralias backported sym))
4646 (make-obsolete backported sym "yasnippet 0.8")
4647 (defalias backported sym))))
4650 (provide 'yasnippet)
4652 ;;; yasnippet.el ends here
4655 ;; byte-compile-warnings: (not cl-functions)