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 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 bound to `yas-trigger-key' which you can customize.
68 ;; M-x yas-load-directory
70 ;; Prompts you for a directory hierarchy of snippets to load.
72 ;; M-x yas-insert-snippet
74 ;; Prompts you for possible snippet expansion if that is
75 ;; possible according to buffer-local and snippet-local
76 ;; expansion conditions. With prefix argument, ignore these
79 ;; M-x yas-visit-snippet-file
81 ;; Prompts you for possible snippet expansions like
82 ;; `yas-insert-snippet', but instead of expanding it, takes
83 ;; you directly to the snippet definition's file, if it
86 ;; M-x yas-new-snippet
88 ;; Lets you create a new snippet file in the correct
89 ;; subdirectory of `yas-snippet-dirs', according to the
92 ;; M-x yas-load-snippet-buffer
94 ;; When editing a snippet, this loads the snippet. This is
95 ;; bound to "C-c C-c" while in the `snippet-mode' editing
98 ;; M-x yas-tryout-snippet
100 ;; When editing a snippet, this opens a new empty buffer,
101 ;; sets it to the appropriate major mode and inserts the
102 ;; snippet there, so you can see what it looks like. This is
103 ;; bound to "C-c C-t" while in `snippet-mode'.
105 ;; M-x yas-describe-tables
107 ;; Lists known snippets in a separate buffer. User is
108 ;; prompted as to whether only the currently active tables
109 ;; are to be displayed, or all the tables for all major
112 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
113 ;; can optionally use it the preferred "prompting method", puting in
114 ;; your .emacs file, for example:
116 ;; (require 'dropdown-list)
117 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
119 ;; yas-completing-prompt))
121 ;; Also check out the customization group
123 ;; M-x customize-group RET yasnippet RET
125 ;; If you use the customization group to set variables
126 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
127 ;; "yasnippet.el" is present in the `load-path' *before* the
128 ;; `custom-set-variables' is executed in your .emacs file.
130 ;; For more information and detailed usage, refer to the project page:
131 ;; http://github.com/capitaomorte/yasnippet
139 ;; Future-proof against obsoleting flet, per discussion at
140 ;; http://github.com/capitaomorte/yasnippet/issues/324
142 (unless (fboundp 'cl-flet)
143 (defalias 'cl-flet 'flet)
144 (put 'cl-flet 'lisp-indent-function 1)
145 (put 'cl-flet 'edebug-form-spec '((&rest (defun*)) cl-declarations body))))
148 ;;; User customizable variables
150 (defgroup yasnippet nil
151 "Yet Another Snippet extension"
154 (defvar yas--load-file-name load-file-name
155 "Store the filename that yasnippet.el was originally loaded from.")
157 (defcustom yas-snippet-dirs (remove nil
158 (list "~/.emacs.d/snippets"
159 (when yas--load-file-name
160 (concat (file-name-directory yas--load-file-name) "snippets"))))
161 "Directory or list of snippet dirs for each major mode.
163 The directory where user-created snippets are to be stored. Can
164 also be a list of directories. In that case, when used for
165 bulk (re)loading of snippets (at startup or via
166 `yas-reload-all'), directories appearing earlier in the list
167 shadow other dir's snippets. Also, the first directory is taken
168 as the default for storing the user's new snippets."
169 :type '(choice (string :tag "Single directory (string)")
170 (repeat :args (string) :tag "List of directories (strings)"))
173 :set #'(lambda (symbol new)
174 (let ((old (and (boundp symbol)
175 (symbol-value symbol))))
176 (set-default symbol new)
177 (unless (or (not (fboundp 'yas-reload-all))
181 (defun yas-snippet-dirs ()
182 "Returns `yas-snippet-dirs' (which see) as a list."
183 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
187 (defcustom yas-prompt-functions '(yas-x-prompt
189 yas-completing-prompt
192 "Functions to prompt for keys, templates, etc interactively.
194 These functions are called with the following arguments:
196 - PROMPT: A string to prompt the user
198 - CHOICES: a list of strings or objects.
200 - optional DISPLAY-FN : A function that, when applied to each of
201 the objects in CHOICES will return a string.
203 The return value of any function you put here should be one of
204 the objects in CHOICES, properly formatted with DISPLAY-FN (if
207 - To signal that your particular style of prompting is
208 unavailable at the moment, you can also have the function return
211 - To signal that the user quit the prompting process, you can
214 (signal 'quit \"user quit!\")."
215 :type '(repeat function)
218 (defcustom yas-indent-line 'auto
219 "Controls indenting applied to a recent snippet expansion.
221 The following values are possible:
223 - `fixed' Indent the snippet to the current column;
225 - `auto' Indent each line of the snippet with `indent-according-to-mode'
227 Every other value means don't apply any snippet-side indendation
228 after expansion (the manual per-line \"$>\" indentation still
230 :type '(choice (const :tag "Nothing" nothing)
231 (const :tag "Fixed" fixed)
232 (const :tag "Auto" auto))
235 (defcustom yas-also-auto-indent-first-line nil
236 "Non-nil means also auto indent first line according to mode.
238 Naturally this is only valid when `yas-indent-line' is `auto'"
242 (defcustom yas-snippet-revival t
243 "Non-nil means re-activate snippet fields after undo/redo."
247 (defcustom yas-trigger-key "<tab>"
248 "The key bound to `yas-expand' when `yas-minor-mode' is active.
250 Value is a string that is converted to the internal Emacs key
251 representation using `read-kbd-macro'."
254 :set #'(lambda (symbol key)
255 (let ((old (and (boundp symbol)
256 (symbol-value symbol))))
257 (set-default symbol key)
258 ;; On very first loading of this defcustom,
259 ;; `yas-trigger-key' is *not* loaded.
260 (if (fboundp 'yas--trigger-key-reload)
261 (yas--trigger-key-reload old)))))
263 (defcustom yas-next-field-key '("TAB" "<tab>")
264 "The key to navigate to next field when a snippet is active.
266 Value is a string that is converted to the internal Emacs key
267 representation using `read-kbd-macro'.
269 Can also be a list of strings."
270 :type '(choice (string :tag "String")
271 (repeat :args (string) :tag "List of strings"))
273 :set #'(lambda (symbol val)
274 (set-default symbol val)
275 (if (fboundp 'yas--init-yas-in-snippet-keymap)
276 (yas--init-yas-in-snippet-keymap))))
279 (defcustom yas-prev-field-key '("<backtab>" "<S-tab>")
280 "The key to navigate to previous field when a snippet is active.
282 Value is a string that is converted to the internal Emacs key
283 representation using `read-kbd-macro'.
285 Can also be a list of strings."
286 :type '(choice (string :tag "String")
287 (repeat :args (string) :tag "List of strings"))
289 :set #'(lambda (symbol val)
290 (set-default symbol val)
291 (if (fboundp 'yas--init-yas-in-snippet-keymap)
292 (yas--init-yas-in-snippet-keymap))))
294 (defcustom yas-skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
295 "The key to clear the currently active field.
297 Value is a string that is converted to the internal Emacs key
298 representation using `read-kbd-macro'.
300 Can also be a list of strings."
301 :type '(choice (string :tag "String")
302 (repeat :args (string) :tag "List of strings"))
304 :set #'(lambda (symbol val)
305 (set-default symbol val)
306 (if (fboundp 'yas--init-yas-in-snippet-keymap)
307 (yas--init-yas-in-snippet-keymap))))
309 (defcustom yas-triggers-in-field nil
310 "If non-nil, `yas-next-field-key' can trigger stacked expansions.
312 Otherwise, `yas-next-field-key' just tries to move on to the next
317 (defcustom yas-fallback-behavior 'call-other-command
318 "How to act when `yas-trigger-key' does *not* expand a snippet.
320 - `call-other-command' means try to temporarily disable YASnippet
321 and call the next command bound to `yas-trigger-key'.
323 - nil or the symbol `return-nil' mean do nothing. (and
324 `yas-expand' returns nil)
326 - A lisp form (apply COMMAND . ARGS) means interactively call
327 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
328 with ARGS as arguments."
329 :type '(choice (const :tag "Call previous command" call-other-command)
330 (const :tag "Do nothing" return-nil))
333 (defcustom yas-choose-keys-first nil
334 "If non-nil, prompt for snippet key first, then for template.
336 Otherwise prompts for all possible snippet names.
338 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
342 (defcustom yas-choose-tables-first nil
343 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
345 Otherwise, user chooses between the merging together of all
348 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
352 (defcustom yas-use-menu 'abbreviate
353 "Display a YASnippet menu in the menu bar.
355 When non-nil, submenus for each snippet table will be listed
356 under the menu \"Yasnippet\".
358 - If set to `abbreviate', only the current major-mode
359 menu and the modes set in `yas-extra-modes' are listed.
361 - If set to `full', every submenu is listed
363 - It set to nil, don't display a menu at all (this requires a
364 `yas-reload-all' call if the menu is already visible).
366 Any other non-nil value, every submenu is listed."
367 :type '(choice (const :tag "Full" full)
368 (const :tag "Abbreviate" abbreviate)
369 (const :tag "No menu" nil))
372 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
373 (char-to-string ?\x21E5) ;; little ->| sign
375 "The text that will be used in menu to represent the trigger."
379 (defcustom yas-wrap-around-region nil
380 "If non-nil, snippet expansion wraps around selected region.
382 The wrapping occurs just before the snippet's exit marker. This
383 can be overriden on a per-snippet basis."
387 (defcustom yas-good-grace t
388 "If non-nil, don't raise errors in inline elisp evaluation.
390 An error string \"[yas] error\" is returned instead."
394 (defcustom yas-visit-from-menu nil
395 "If non-nil visit snippets's files from menu, instead of expanding them.
397 This cafn only work when snippets are loaded from files."
401 (defcustom yas-expand-only-for-last-commands nil
402 "List of `last-command' values to restrict tab-triggering to, or nil.
404 Leave this set at nil (the default) to be able to trigger an
405 expansion simply by placing the cursor after a valid tab trigger,
406 using whichever commands.
408 Optionallly, set this to something like '(self-insert-command) if
409 you to wish restrict expansion to only happen when the last
410 letter of the snippet tab trigger was typed immediately before
411 the trigger key itself."
412 :type '(repeat function)
415 ;; Only two faces, and one of them shouldn't even be used...
417 (defface yas-field-highlight-face
418 '((t (:inherit 'region)))
419 "The face used to highlight the currently active field of a snippet"
422 (defface yas--field-debug-face
424 "The face used for debugging some overlays normally hidden"
428 ;;; User can also customize the next defvars
430 (defun yas--define-some-keys (keys keymap definition)
431 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
432 (let ((keys (or (and (listp keys) keys)
435 (define-key keymap (read-kbd-macro key) definition))))
437 (defun yas--init-yas-in-snippet-keymap ()
439 (let ((map (make-sparse-keymap)))
440 (mapc #'(lambda (binding)
441 (yas--define-some-keys (car binding) map (cdr binding)))
442 `((,yas-next-field-key . yas-next-field-or-maybe-expand)
443 (,yas-prev-field-key . yas-prev-field)
444 ("C-g" . yas-abort-snippet)
445 (,yas-skip-and-clear-key . yas-skip-and-clear-or-delete-char)))
448 (defvar yas-keymap (yas--init-yas-in-snippet-keymap)
449 "The keymap active while a snippet expansion is in progress.")
451 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
452 "List of character syntaxes used to find a trigger key before point.
453 The list is tried in the order while scanning characters
454 backwards from point. For example, if the list is '(\"w\" \"w_\")
455 first look for trigger keys which are composed exclusively of
456 \"word\"-syntax characters, and then, if that fails, look for
457 keys which are either of \"word\" or \"symbol\"
458 syntax. Triggering after
462 will, according to the \"w\" element first try \"bar\". If that
463 isn't a trigger key, \"foo-bar\" is tried, respecting a second
466 (defvar yas-after-exit-snippet-hook
468 "Hooks to run after a snippet exited.
470 The hooks will be run in an environment where some variables bound to
473 `yas-snippet-beg' : The beginning of the region of the snippet.
475 `yas-snippet-end' : Similar to beg.
477 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
479 (defvar yas-before-expand-snippet-hook
481 "Hooks to run just before expanding a snippet.")
483 (defvar yas-buffer-local-condition
484 '(if (and (or (fourth (syntax-ppss))
485 (fifth (syntax-ppss)))
486 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
487 '(require-snippet-condition . force-in-comment)
489 "Snippet expanding condition.
491 This variable is a lisp form which is evaluated everytime a
492 snippet expansion is attemped:
494 * If it evaluates to nil, no snippets can be expanded.
496 * If it evaluates to the a cons (require-snippet-condition
499 * Snippets bearing no \"# condition:\" directive are not
502 * Snippets bearing conditions that evaluate to nil (or
503 produce an error) won't be onsidered.
505 * If the snippet has a condition that evaluates to non-nil
508 * If REQUIREMENT is t, the snippet is considered
510 * If REQUIREMENT is `eq' RESULT, the snippet is
513 * Otherwise, the snippet is not considered.
515 * If it evaluates to the symbol 'always, all snippets are
516 considered for expansion, regardless of any conditions.
518 * If it evaluates to t or some other non-nil value
520 * Snippet bearing no conditions, or conditions that
521 evaluate to non-nil, are considered for expansion.
523 * Otherwise, the snippet is not considered.
525 Here's an example preventing snippets from being expanded from
526 inside comments, in `python-mode' only, with the exception of
527 snippets returning the symbol 'force-in-comment in their
530 (add-hook 'python-mode-hook
532 (setq yas-buffer-local-condition
533 '(if (python-in-string/comment)
534 '(require-snippet-condition . force-in-comment)
537 The default value is similar, it filters out potential snippet
538 expansions inside comments and string literals, unless the
539 snippet itself contains a condition that returns the symbol
540 `force-in-comment'.")
543 ;;; Internal variables
545 (defvar yas--version "0.8.0 (beta)")
547 (defvar yas--menu-table (make-hash-table)
548 "A hash table of MAJOR-MODE symbols to menu keymaps.")
550 (defvar yas--known-modes
551 '(ruby-mode rst-mode markdown-mode)
552 "A list of mode which is well known but not part of emacs.")
554 (defvar yas--escaped-characters
555 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
556 "List of characters which *might* need to be escaped.")
558 (defconst yas--field-regexp
559 "${\\([0-9]+:\\)?\\([^}]*\\)}"
560 "A regexp to *almost* recognize a field.")
562 (defconst yas--multi-dollar-lisp-expression-regexp
563 "$+[ \t\n]*\\(([^)]*)\\)"
564 "A regexp to *almost* recognize a \"$(...)\" expression.")
566 (defconst yas--backquote-lisp-expression-regexp
568 "A regexp to recognize a \"`lisp-expression`\" expression." )
570 (defconst yas--transform-mirror-regexp
571 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
572 "A regexp to *almost* recognize a mirror with a transform.")
574 (defconst yas--simple-mirror-regexp
576 "A regexp to recognize a simple mirror.")
578 (defvar yas--snippet-id-seed 0
579 "Contains the next id for a snippet.")
581 (defun yas--snippet-next-id ()
582 (let ((id yas--snippet-id-seed))
583 (incf yas--snippet-id-seed)
589 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
590 (defvar last-buffer-undo-list nil)
592 (defvar yas--minor-mode-menu nil
593 "Holds the YASnippet menu")
595 (defun yas--init-minor-keymap ()
596 (let ((map (make-sparse-keymap)))
598 (easy-menu-define yas--minor-mode-menu
600 "Menu used when `yas-minor-mode' is active."
603 ["Expand trigger" yas-expand
604 :help "Possibly expand tab trigger before point"]
605 ["Insert at point..." yas-insert-snippet
606 :help "Prompt for an expandable snippet and expand it at point"]
607 ["New snippet..." yas-new-snippet
608 :help "Create a new snippet in an appropriate directory"]
609 ["Visit snippet file..." yas-visit-snippet-file
610 :help "Prompt for an expandable snippet and find its file"]
612 ("Snippet menu behaviour"
613 ["Visit snippets" (setq yas-visit-from-menu t)
614 :help "Visit snippets from the menu"
615 :active t :style radio :selected yas-visit-from-menu]
616 ["Expand snippets" (setq yas-visit-from-menu nil)
617 :help "Expand snippets from the menu"
618 :active t :style radio :selected (not yas-visit-from-menu)]
620 ["Show all known modes" (setq yas-use-menu 'full)
621 :help "Show one snippet submenu for each loaded table"
622 :active t :style radio :selected (eq yas-use-menu 'full)]
623 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
624 :help "Show only snippet submenus for the current active modes"
625 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
627 ["Auto" (setq yas-indent-line 'auto)
628 :help "Indent each line of the snippet with `indent-according-to-mode'"
629 :active t :style radio :selected (eq yas-indent-line 'auto)]
630 ["Fixed" (setq yas-indent-line 'fixed)
631 :help "Indent the snippet to the current column"
632 :active t :style radio :selected (eq yas-indent-line 'fixed)]
633 ["None" (setq yas-indent-line 'none)
634 :help "Don't apply any particular snippet indentation after expansion"
635 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
637 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
638 (not yas-also-auto-indent-first-line))
639 :help "When auto-indenting also, auto indent the first line menu"
640 :active (eq yas-indent-line 'auto)
641 :style toggle :selected yas-also-auto-indent-first-line]
644 ["System X-widget" (setq yas-prompt-functions
646 (remove 'yas-x-prompt
647 yas-prompt-functions)))
648 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
649 :active t :style radio :selected (eq (car yas-prompt-functions)
651 ["Dropdown-list" (setq yas-prompt-functions
652 (cons 'yas-dropdown-prompt
653 (remove 'yas-dropdown-prompt
654 yas-prompt-functions)))
655 :help "Use a special dropdown list"
656 :active t :style radio :selected (eq (car yas-prompt-functions)
657 'yas-dropdown-prompt)]
658 ["Ido" (setq yas-prompt-functions
659 (cons 'yas-ido-prompt
660 (remove 'yas-ido-prompt
661 yas-prompt-functions)))
662 :help "Use an ido-style minibuffer prompt"
663 :active t :style radio :selected (eq (car yas-prompt-functions)
665 ["Completing read" (setq yas-prompt-functions
666 (cons 'yas-completing-prompt
667 (remove 'yas-completing-prompt
668 yas-prompt-functions)))
669 :help "Use a normal minibuffer prompt"
670 :active t :style radio :selected (eq (car yas-prompt-functions)
671 'yas-completing-prompt)]
674 ["Wrap region in exit marker"
675 (setq yas-wrap-around-region
676 (not yas-wrap-around-region))
677 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
678 :style toggle :selected yas-wrap-around-region]
679 ["Allow stacked expansions "
680 (setq yas-triggers-in-field
681 (not yas-triggers-in-field))
682 :help "If non-nil allow snippets to be triggered inside other snippet fields"
683 :style toggle :selected yas-triggers-in-field]
684 ["Revive snippets on undo "
685 (setq yas-snippet-revival
686 (not yas-snippet-revival))
687 :help "If non-nil allow snippets to become active again after undo"
688 :style toggle :selected yas-snippet-revival]
691 (not yas-good-grace))
692 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
693 :style toggle :selected yas-good-grace]
696 ["Load snippets..." yas-load-directory
697 :help "Load snippets from a specific directory"]
698 ["Reload everything" yas-reload-all
699 :help "Cleanup stuff, reload snippets, rebuild menus"]
701 :help "Display some information about YASsnippet"])))
703 ;; Now for the stuff that has direct keybindings
705 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
706 (define-key map "\C-c&\C-n" 'yas-new-snippet)
707 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
710 (defvar yas-minor-mode-map (yas--init-minor-keymap)
711 "The keymap used when `yas-minor-mode' is active.")
713 (defun yas--trigger-key-reload (&optional unbind-key)
714 "Rebind `yas-expand' to the new value of `yas-trigger-key'.
716 With optional UNBIND-KEY, try to unbind that key from
717 `yas-minor-mode-map'."
718 (when (and unbind-key
720 (not (string= unbind-key "")))
721 (define-key yas-minor-mode-map (read-kbd-macro unbind-key) nil))
722 (when (and yas-trigger-key
723 (stringp yas-trigger-key)
724 (not (string= yas-trigger-key "")))
725 (define-key yas-minor-mode-map (read-kbd-macro yas-trigger-key) 'yas-expand)))
727 (defvar yas--tables (make-hash-table)
728 "A hash table of mode symbols to `yas--table' objects.")
730 (defvar yas--parents (make-hash-table)
731 "A hash table of mode symbols do lists of direct parent mode symbols.
733 This list is populated when reading the \".yas-parents\" files
734 found when traversing snippet directories with
735 `yas-load-directory'.
737 There might be additionalal parenting information stored in the
738 `derived-mode-parent' property of some mode symbols, but that is
741 (defvar yas--direct-keymaps (list)
742 "Keymap alist supporting direct snippet keybindings.
744 This variable is is placed in `emulation-mode-map-alists'.
746 Its elements looks like (TABLE-NAME . KEYMAP). They're
747 instantiated on `yas-reload-all' but KEYMAP is added to only when
748 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
749 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
750 defined direct keybindings to the command
751 `yas-expand-from-keymap' which then which snippet to expand.")
753 (defun yas-direct-keymaps-reload ()
754 "Force reload the direct keybinding for active snippet tables."
756 (setq yas--direct-keymaps nil)
757 (maphash #'(lambda (name table)
758 (push (cons (intern (format "yas--direct-%s" name))
759 (yas--table-direct-keymap table))
760 yas--direct-keymaps))
763 (defun yas--modes-to-activate ()
764 "Compute list of mode symbols that are active for `yas-expand'
766 (let ((modes-to-activate (list major-mode))
768 (while (setq mode (get mode 'derived-mode-parent))
769 (push mode modes-to-activate))
770 (dolist (mode (yas-extra-modes))
771 (push mode modes-to-activate))
773 (append modes-to-activate
774 (mapcan #'(lambda (mode)
775 (yas--all-parents mode))
776 modes-to-activate)))))
778 (defvar yas-minor-mode-hook nil
779 "Hook run when yas-minor-mode is turned on")
782 (define-minor-mode yas-minor-mode
783 "Toggle YASnippet mode.
785 When YASnippet mode is enabled, the `yas-trigger-key' key expands
786 snippets of code depending on the major mode.
788 With no argument, this command toggles the mode.
789 positive prefix argument turns on the mode.
790 Negative prefix argument turns off the mode.
792 You can customize the key through `yas-trigger-key'.
795 \\{yas-minor-mode-map}"
797 ;; The indicator for the mode line.
800 (cond (yas-minor-mode
801 ;; Reload the trigger key
803 (yas--trigger-key-reload)
804 ;; Install the direct keymaps in `emulation-mode-map-alists'
805 ;; (we use `add-hook' even though it's not technically a hook,
806 ;; but it works). Then define variables named after modes to
807 ;; index `yas--direct-keymaps'.
809 ;; Also install the post-command-hook.
811 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
812 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
813 ;; Set the `yas--direct-%s' vars for direct keymap expansion
815 (dolist (mode (yas--modes-to-activate))
816 (let ((name (intern (format "yas--direct-%s" mode))))
817 (set-default name nil)
818 (set (make-local-variable name) t)))
821 (yas--load-pending-jits))
823 ;; Uninstall the direct keymaps and the post-command hook
825 (remove-hook 'post-command-hook 'yas--post-command-handler t)
826 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
828 (defvar yas--dont-activate '(minibufferp)
829 "If non-nil don't let `yas-minor-mode-on' active yas for this buffer.
831 If a function, then its result is used.
833 If a list of functions, then all functions must return nil to
834 activate yas for this buffer.
836 `yas-minor-mode-on' is usually called by `yas-global-mode' so
837 this effectively lets you define exceptions to the \"global\"
838 behaviour. Can also be a function of zero arguments.")
839 (make-variable-buffer-local 'yas--dont-activate)
841 (defun yas-minor-mode-on ()
842 "Turn on YASnippet minor mode.
844 Do this unless `yas--dont-activate' is truish "
846 (unless (cond ((functionp yas--dont-activate)
847 (funcall yas--dont-activate))
848 ((consp yas--dont-activate)
849 (some #'funcall yas--dont-activate))
850 (yas--dont-activate))
851 ;; Load all snippets definitions unless we still don't have a
852 ;; root-directory or some snippets have already been loaded.
857 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
861 (defun yas--global-mode-reload-with-jit-maybe ()
862 (when yas-global-mode (yas-reload-all)))
864 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
866 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
869 (defvar yas--font-lock-keywords
870 (append '(("^#.*$" . font-lock-comment-face))
871 lisp-font-lock-keywords
872 lisp-font-lock-keywords-1
873 lisp-font-lock-keywords-2
875 (0 font-lock-keyword-face)
876 (1 font-lock-string-face t))
878 (0 font-lock-keyword-face)
879 (1 font-lock-warning-face t))
880 ("${" font-lock-keyword-face)
881 ("$[0-9]+?" font-lock-preprocessor-face)
882 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
884 (0 font-lock-keyword-face)))))
886 (defun yas--init-major-keymap ()
887 (let ((map (make-sparse-keymap)))
888 (easy-menu-define nil
890 "Menu used when snippet-mode is active."
892 (mapcar #'(lambda (ent)
894 (define-key map (third ent) (second ent)))
895 (vector (first ent) (second ent) t))
897 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
898 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
901 (defvar snippet-mode-map
902 (yas--init-major-keymap)
903 "The keymap used when `snippet-mode' is active")
906 (define-derived-mode snippet-mode text-mode "Snippet"
907 "A mode for editing yasnippets"
908 (setq font-lock-defaults '(yas--font-lock-keywords))
909 (set (make-local-variable 'require-final-newline) nil)
910 (set (make-local-variable 'comment-start) "#")
911 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
915 ;;; Internal structs for template management
917 (defstruct (yas--template (:constructor yas--make-blank-template))
918 "A template for a snippet."
928 group ;; as dictated by the #group: directive or .yas-make-groups
929 perm-group ;; as dictated by `yas-define-menu'
933 (defun yas--populate-template (template &rest args)
934 "Helper function to populate a template with properties"
938 (position (intern (substring (symbol-name (car args)) 1))
939 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
941 (setq args (cddr args)))
944 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
945 "A table to store snippets for a particular mode.
947 Has the following fields:
951 A symbol name normally corresponding to a major mode, but can
952 also be a pseudo major-mode to be referenced in
953 `yas-extra-modes', for example.
957 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
958 a string or a vector, where the former is the snippet's trigger
959 and the latter means it's a direct keybinding. NAMEHASH is yet
960 another hash of (NAME . TEMPLATE) where NAME is the snippet's
961 name and TEMPLATE is a `yas--template' object.
963 `yas--table-direct-keymap'
965 A keymap for the snippets in this table that have direct
966 keybindings. This is kept in sync with the keyhash, i.e., all
967 the elements of the keyhash that are vectors appear here as
968 bindings to `yas-expand-from-keymap'.
970 `yas--table-uuidhash'
972 A hash table mapping snippets uuid's to the same `yas--template'
973 objects. A snippet uuid defaults to the snippet's name.
976 (hash (make-hash-table :test 'equal))
977 (uuidhash (make-hash-table :test 'equal))
979 (direct-keymap (make-sparse-keymap)))
981 (defun yas--get-template-by-uuid (mode uuid)
982 "Find the snippet template in MODE by its UUID."
983 (let* ((table (gethash mode yas--tables mode)))
985 (gethash uuid (yas--table-uuidhash table)))))
987 ;; Apropos storing/updating in TABLE, this works in two steps:
989 ;; 1. `yas--remove-template-by-uuid' removes any
990 ;; keyhash-namehash-template mappings from TABLE, grabing the
991 ;; snippet by its uuid. Also removes mappings from TABLE's
992 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
993 ;; of potentially stale menu bindings right?.)
995 ;; 2. `yas--add-template' adds this all over again.
997 ;; Create a new or add to an existing keyhash-namehash mapping.
999 ;; For reference on understanding this, consider three snippet
1002 ;; A: # name: The Foo
1004 ;; # binding: C-c M-l
1006 ;; B: # name: Mrs Foo
1009 ;; C: # name: The Bar
1010 ;; # binding: C-c M-l
1015 ;; keyhash namehashes(3) yas--template structs(4)
1016 ;; -----------------------------------------------------
1019 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1020 ;; "Mrs Foo" ---> [yas--template B] |
1022 ;; [C-c M-l] ---> "The Foo" -------------------------/
1023 ;; "The Bar" ---> [yas--template C]
1025 ;; "baz" ---> "Baz" ---> [yas--template D]
1027 ;; Additionally, since uuid defaults to the name, we have a
1028 ;; `yas--table-uuidhash' for TABLE
1030 ;; uuidhash yas--template structs
1031 ;; -------------------------------
1032 ;; "The Foo" ---> [yas--template A]
1033 ;; "Mrs Foo" ---> [yas--template B]
1034 ;; "The Bar" ---> [yas--template C]
1035 ;; "Baz" ---> [yas--template D]
1037 ;; FIXME: the more I look at this data-structure the more I think I'm
1038 ;; stupid. There has to be an easier way (but beware lots of code
1039 ;; depends on this).
1041 (defun yas--remove-template-by-uuid (table uuid)
1042 "Remove from TABLE a template identified by UUID."
1043 (let ((template (gethash uuid (yas--table-uuidhash table))))
1045 (let* ((name (yas--template-name template))
1047 ;; Remove the name from each of the targeted namehashes
1049 (maphash #'(lambda (k v)
1050 (let ((template (gethash name v)))
1052 (eq uuid (yas--template-uuid template)))
1054 (when (zerop (hash-table-count v))
1055 (push k empty-keys)))))
1056 (yas--table-hash table))
1057 ;; Remove the namehash themselves if they've become empty
1059 (dolist (key empty-keys)
1061 (define-key (yas--table-direct-keymap table) key nil))
1062 (remhash key (yas--table-hash table)))
1064 ;; Finally, remove the uuid from the uuidhash
1066 (remhash uuid (yas--table-uuidhash table))))))
1068 (defun yas--add-template (table template)
1069 "Store in TABLE the snippet template TEMPLATE.
1071 KEY can be a string (trigger key) of a vector (direct
1073 (let ((name (yas--template-name template))
1074 (key (yas--template-key template))
1075 (keybinding (yas--template-keybinding template))
1076 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1077 (dolist (k (remove nil (list key keybinding)))
1081 (yas--table-hash table))
1083 (make-hash-table :test 'equal)
1084 (yas--table-hash table))))
1086 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1088 ;; Update TABLE's `yas--table-uuidhash'
1089 (puthash (yas--template-uuid template)
1091 (yas--table-uuidhash table))))
1093 (defun yas--update-template (table template)
1094 "Add or update TEMPLATE in TABLE.
1096 Also takes care of adding and updating to the associated menu."
1097 ;; Remove from table by uuid
1099 (yas--remove-template-by-uuid table (yas--template-uuid template))
1100 ;; Add to table again
1102 (yas--add-template table template)
1103 ;; Take care of the menu
1106 (yas--update-template-menu table template)))
1108 (defun yas--update-template-menu (table template)
1109 "Update every menu-related for TEMPLATE"
1110 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1111 (key (yas--template-key template))
1112 (keybinding (yas--template-keybinding template)))
1113 ;; The snippet might have changed name or keys, so update
1114 ;; user-visible strings
1116 (unless (eq (cdr menu-binding-pair) :none)
1117 ;; the menu item name
1119 (setf (cadar menu-binding-pair) (yas--template-name template))
1120 ;; the :keys information (also visible to the user)
1121 (setf (getf (cdr (car menu-binding-pair)) :keys)
1122 (or (and keybinding (key-description keybinding))
1123 (and key (concat key yas-trigger-symbol))))))
1124 (unless (yas--template-menu-managed-by-yas-define-menu template)
1126 (yas--menu-keymap-get-create (yas--table-mode table)
1127 (mapcar #'yas--table-mode
1128 (yas--table-parents table))))
1129 (group (yas--template-group template)))
1130 ;; Remove from menu keymap
1132 (assert menu-keymap)
1133 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1135 ;; Add necessary subgroups as necessary.
1137 (dolist (subgroup group)
1138 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1139 (unless (and subgroup-keymap
1140 (keymapp subgroup-keymap))
1141 (setq subgroup-keymap (make-sparse-keymap))
1142 (define-key menu-keymap (vector (make-symbol subgroup))
1143 `(menu-item ,subgroup ,subgroup-keymap)))
1144 (setq menu-keymap subgroup-keymap)))
1146 ;; Add this entry to the keymap
1148 (define-key menu-keymap
1149 (vector (make-symbol (yas--template-uuid template)))
1150 (car (yas--template-menu-binding-pair template))))))
1152 (defun yas--namehash-templates-alist (namehash)
1154 (maphash #'(lambda (k v)
1155 (push (cons k v) alist))
1159 (defun yas--fetch (table key)
1160 "Fetch templates in TABLE by KEY.
1162 Return a list of cons (NAME . TEMPLATE) where NAME is a
1163 string and TEMPLATE is a `yas--template' structure."
1164 (let* ((keyhash (yas--table-hash table))
1165 (namehash (and keyhash (gethash key keyhash))))
1167 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1170 ;;; Filtering/condition logic
1172 (defun yas--eval-condition (condition)
1179 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1183 (defun yas--filter-templates-by-condition (templates)
1184 "Filter the templates using the applicable condition.
1186 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1187 string and TEMPLATE is a `yas--template' structure.
1189 This function implements the rules described in
1190 `yas-buffer-local-condition'. See that variables documentation."
1191 (let ((requirement (yas--require-template-specific-condition-p)))
1192 (if (eq requirement 'always)
1194 (remove-if-not #'(lambda (pair)
1195 (yas--template-can-expand-p
1196 (yas--template-condition (cdr pair)) requirement))
1199 (defun yas--require-template-specific-condition-p ()
1200 "Decides if this buffer requests/requires snippet-specific
1201 conditions to filter out potential expansions."
1202 (if (eq 'always yas-buffer-local-condition)
1204 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1205 (yas--eval-condition yas-buffer-local-condition))
1206 yas-buffer-local-condition)))
1207 (when local-condition
1208 (if (eq local-condition t)
1210 (and (consp local-condition)
1211 (eq 'require-snippet-condition (car local-condition))
1212 (symbolp (cdr local-condition))
1213 (cdr local-condition)))))))
1215 (defun yas--template-can-expand-p (condition requirement)
1216 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1217 (let* ((result (or (null condition)
1218 (yas--eval-condition condition))))
1219 (cond ((eq requirement t)
1222 (eq requirement result)))))
1224 (defun yas--all-parents (mode)
1225 "Returns a list of all parent modes of MODE"
1226 (let ((parents (gethash mode yas--parents)))
1228 (mapcan #'yas--all-parents parents))))
1230 (defun yas--table-templates (table)
1233 (maphash #'(lambda (key namehash)
1234 (maphash #'(lambda (name template)
1235 (push (cons name template) acc))
1237 (yas--table-hash table))
1238 (yas--filter-templates-by-condition acc))))
1240 (defun yas--current-key ()
1241 "Get the key under current position. A key is used to find
1242 the template of a snippet in the current snippet-table."
1243 (let ((start (point))
1245 (syntaxes yas-key-syntaxes)
1249 (while (and (not done) syntaxes)
1250 (setq syntax (car syntaxes))
1251 (setq syntaxes (cdr syntaxes))
1253 (skip-syntax-backward syntax)
1254 (setq start (point)))
1256 (mapcan #'(lambda (table)
1257 (yas--fetch table (buffer-substring-no-properties start end)))
1258 (yas--get-snippet-tables)))
1267 (defun yas--table-all-keys (table)
1268 "Get trigger keys of all active snippets in TABLE"
1270 (maphash #'(lambda (key namehash)
1271 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1273 (yas--table-hash table))
1276 (defun yas--table-mode (table)
1277 (intern (yas--table-name table)))
1280 ;;; Internal functions:
1282 (defun yas--real-mode? (mode)
1283 "Try to find out if MODE is a real mode. The MODE bound to
1284 a function (like `c-mode') is considered real mode. Other well
1285 known mode like `ruby-mode' which is not part of Emacs might
1286 not bound to a function until it is loaded. So yasnippet keeps
1287 a list of modes like this to help the judgement."
1289 (find mode yas--known-modes)))
1291 (defun yas--eval-lisp (form)
1292 "Evaluate FORM and convert the result to string."
1293 (let ((retval (catch 'yas--exception
1299 (let ((result (eval form)))
1301 (format "%s" result))))))
1302 (error (if yas-good-grace
1303 (yas--format "elisp error! %s" (error-message-string err))
1304 (error (yas--format "elisp error: %s"
1305 (error-message-string err)))))))))
1306 (when (and (consp retval)
1307 (eq 'yas--exception (car retval)))
1308 (error (cdr retval)))
1311 (defun yas--eval-lisp-no-saves (form)
1314 (error (if yas-good-grace
1315 (yas--format "elisp error! %s" (error-message-string err))
1316 (error (yas--format "elisp error: %s"
1317 (error-message-string err)))))))
1319 (defun yas--read-lisp (string &optional nil-on-error)
1320 "Read STRING as a elisp expression and return it.
1322 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1323 return an expression that when evaluated will issue an error."
1326 (error (and (not nil-on-error)
1327 `(error (error-message-string ,err))))))
1329 (defun yas--read-keybinding (keybinding)
1330 "Read KEYBINDING as a snippet keybinding, return a vector."
1331 (when (and keybinding
1332 (not (string-match "keybinding" keybinding)))
1334 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1336 (read-kbd-macro keybinding 'need-vector))))
1339 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1340 keybinding (error-message-string err))
1343 (defvar yas-extra-modes nil
1344 "If non-nil, also lookup snippets for this/these modes.
1346 Can be a symbol or a list of symbols.
1348 This variable probably makes more sense as buffer-local, so
1349 ensure your use `make-local-variable' when you set it.")
1350 (defun yas-extra-modes ()
1351 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1352 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1354 (defun yas--table-get-create (mode)
1355 "Get or create the snippet table corresponding to MODE."
1356 (let ((table (gethash mode
1359 (setq table (yas--make-snippet-table (symbol-name mode)))
1360 (puthash mode table yas--tables)
1361 (push (cons (intern (format "yas--direct-%s" mode))
1362 (yas--table-direct-keymap table))
1363 yas--direct-keymaps))
1366 (defun yas--get-snippet-tables ()
1367 "Get snippet tables for current buffer.
1369 Return a list of `yas--table' objects. The list of modes to
1370 consider is returned by `yas--modes-to-activate'"
1372 (mapcar #'(lambda (mode-name)
1373 (gethash mode-name yas--tables))
1374 (yas--modes-to-activate))))
1376 (defun yas--menu-keymap-get-create (mode &optional parents)
1377 "Get or create the menu keymap for MODE and its PARENTS.
1379 This may very well create a plethora of menu keymaps and arrange
1380 them all in `yas--menu-table'"
1381 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1382 (puthash mode (make-sparse-keymap) yas--menu-table))))
1383 (mapc #'yas--menu-keymap-get-create parents)
1384 (define-key yas--minor-mode-menu (vector mode)
1385 `(menu-item ,(symbol-name mode) ,menu-keymap
1386 :visible (yas--show-menu-p ',mode)))
1389 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1390 ;;; Template-related and snippet loading functions
1392 (defun yas--parse-template (&optional file)
1393 "Parse the template in the current buffer.
1395 Optional FILE is the absolute file name of the file being
1398 Optional GROUP is the group where the template is to go,
1399 otherwise we attempt to calculate it from FILE.
1401 Return a snippet-definition, i.e. a list
1403 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1405 If the buffer contains a line of \"# --\" then the contents above
1406 this line are ignored. Directives can set most of these with the syntax:
1408 # directive-name : directive-value
1410 Here's a list of currently recognized directives:
1421 (goto-char (point-min))
1422 (let* ((type 'snippet)
1424 (file-name-nondirectory file)))
1430 (yas--calculate-group file)))
1434 (if (re-search-forward "^# --\n" nil t)
1435 (progn (setq template
1436 (buffer-substring-no-properties (point)
1438 (setq bound (point))
1439 (goto-char (point-min))
1440 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1441 (when (string= "uuid" (match-string-no-properties 1))
1442 (setq uuid (match-string-no-properties 2)))
1443 (when (string= "type" (match-string-no-properties 1))
1444 (setq type (if (string= "command" (match-string-no-properties 2))
1447 (when (string= "key" (match-string-no-properties 1))
1448 (setq key (match-string-no-properties 2)))
1449 (when (string= "name" (match-string-no-properties 1))
1450 (setq name (match-string-no-properties 2)))
1451 (when (string= "condition" (match-string-no-properties 1))
1452 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1453 (when (string= "group" (match-string-no-properties 1))
1454 (setq group (match-string-no-properties 2)))
1455 (when (string= "expand-env" (match-string-no-properties 1))
1456 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1458 (when (string= "binding" (match-string-no-properties 1))
1459 (setq binding (match-string-no-properties 2)))))
1461 (buffer-substring-no-properties (point-min) (point-max))))
1462 (unless (or key binding)
1463 (setq key (and file (file-name-nondirectory file))))
1464 (when (eq type 'command)
1465 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1467 (setq group (split-string group "\\.")))
1468 (list key template name condition group expand-env file binding uuid)))
1470 (defun yas--calculate-group (file)
1471 "Calculate the group for snippet file path FILE."
1472 (let* ((dominating-dir (locate-dominating-file file
1473 ".yas-make-groups"))
1474 (extra-path (and dominating-dir
1475 (replace-regexp-in-string (concat "^"
1476 (expand-file-name dominating-dir))
1478 (expand-file-name file))))
1479 (extra-dir (and extra-path
1480 (file-name-directory extra-path)))
1481 (group (and extra-dir
1482 (replace-regexp-in-string "/"
1484 (directory-file-name extra-dir)))))
1487 (defun yas--subdirs (directory &optional filep)
1488 "Return subdirs or files of DIRECTORY according to FILEP."
1489 (remove-if (lambda (file)
1490 (or (string-match "^\\."
1491 (file-name-nondirectory file))
1492 (string-match "^#.*#$"
1493 (file-name-nondirectory file))
1495 (file-name-nondirectory file))
1497 (file-directory-p file)
1498 (not (file-directory-p file)))))
1499 (directory-files directory t)))
1501 (defun yas--make-menu-binding (template)
1502 (let ((mode (yas--table-mode (yas--template-table template))))
1503 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1505 (defun yas--expand-or-visit-from-menu (mode uuid)
1506 (let* ((table (yas--table-get-create mode))
1507 (yas--current-template (and table
1508 (gethash uuid (yas--table-uuidhash table)))))
1509 (when yas--current-template
1510 (if yas-visit-from-menu
1511 (yas--visit-snippet-file-1 yas--current-template)
1512 (let ((where (if (region-active-p)
1513 (cons (region-beginning) (region-end))
1514 (cons (point) (point)))))
1515 (yas-expand-snippet (yas--template-content yas--current-template)
1518 (yas--template-expand-env yas--current-template)))))))
1520 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1521 ;; Popping up for keys and templates
1523 (defvar yas--x-pretty-prompt-templates nil
1524 "If non-nil, attempt to prompt for templates like TextMate.")
1527 (defun yas--prompt-for-template (templates &optional prompt)
1528 "Interactively choose a template from the list TEMPLATES.
1530 TEMPLATES is a list of `yas--template'."
1533 (sort templates #'(lambda (t1 t2)
1534 (< (length (yas--template-name t1))
1535 (length (yas--template-name t2))))))
1536 (if yas--x-pretty-prompt-templates
1537 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1538 (some #'(lambda (fn)
1539 (funcall fn (or prompt "Choose a snippet: ")
1541 #'yas--template-name))
1542 yas-prompt-functions))))
1544 (defun yas--prompt-for-keys (keys &optional prompt)
1545 "Interactively choose a template key from the list KEYS."
1547 (some #'(lambda (fn)
1548 (funcall fn (or prompt "Choose a snippet key: ") keys))
1549 yas-prompt-functions)))
1551 (defun yas--prompt-for-table (tables &optional prompt)
1553 (some #'(lambda (fn)
1554 (funcall fn (or prompt "Choose a snippet table: ")
1557 yas-prompt-functions)))
1559 (defun yas-x-prompt (prompt choices &optional display-fn)
1560 "Display choices in a x-window prompt."
1561 ;; FIXME: HACK: if we notice that one of the objects in choices is
1562 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1564 ;; This would be better implemented by passing CHOICES as a
1565 ;; strucutred tree rather than a list. Modifications would go as far
1566 ;; up as `yas--all-templates' I think.
1568 (when (and window-system choices)
1570 (let (menu d) ;; d for display
1572 (setq d (or (and display-fn (funcall display-fn c))
1575 (push (cons (concat " " d) c) menu))
1577 (push (car d) menu))))
1578 (setq menu (list prompt (push "title" menu)))
1579 (x-popup-menu (if (fboundp 'posn-at-point)
1580 (let ((x-y (posn-x-y (posn-at-point (point)))))
1581 (list (list (+ (car x-y) 10)
1589 (defun yas--x-pretty-prompt-templates (prompt templates)
1590 "Display TEMPLATES, grouping neatly by table name."
1591 (let ((organized (make-hash-table :test #'equal))
1595 (dolist (tl templates)
1596 (puthash (yas--template-table tl)
1598 (gethash (yas--template-table tl) organized))
1600 (setq more-than-one-table (> (hash-table-count organized) 1))
1601 (setq prefix (if more-than-one-table
1603 (if more-than-one-table
1604 (maphash #'(lambda (table templates)
1605 (push (yas--table-name table) menu)
1606 (dolist (tl templates)
1607 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1608 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1610 (setq menu (nreverse menu))
1611 (or (x-popup-menu (if (fboundp 'posn-at-point)
1612 (let ((x-y (posn-x-y (posn-at-point (point)))))
1613 (list (list (+ (car x-y) 10)
1617 (list prompt (push "title" menu)))
1620 (defun yas-ido-prompt (prompt choices &optional display-fn)
1621 (when (and (fboundp 'ido-completing-read)
1622 (or (>= emacs-major-version 24)
1624 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1626 (eval-when-compile (require 'dropdown-list nil t))
1627 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1628 (when (featurep 'dropdown-list)
1629 (let (formatted-choices
1633 (dolist (choice choices)
1634 (setq d (or (and display-fn (funcall display-fn choice))
1637 (push d formatted-choices)
1638 (push choice filtered-choices)))
1640 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1642 (nth n filtered-choices)
1645 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1646 (let (formatted-choices
1650 (completion-fn (or completion-fn
1651 #'completing-read)))
1652 (dolist (choice choices)
1653 (setq d (or (and display-fn (funcall display-fn choice))
1656 (push d formatted-choices)
1657 (push choice filtered-choices)))
1658 (setq chosen (and formatted-choices
1659 (funcall completion-fn prompt
1665 (let ((position (or (and chosen
1666 (position chosen formatted-choices :test #'string=))
1668 (nth position filtered-choices))))
1670 (defun yas-no-prompt (prompt choices &optional display-fn)
1673 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1674 ;; Loading snippets from files
1676 (defun yas--load-yas-setup-file (file)
1677 (load file 'noerror))
1679 (defun yas-load-directory (top-level-dir &optional use-jit)
1680 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1682 Below TOP-LEVEL-DIR each directory should be a mode name.
1684 Optional USE-JIT use jit-loading of snippets."
1685 (interactive "DSelect the root directory: ")
1686 (unless yas-snippet-dirs
1687 (setq yas-snippet-dirs top-level-dir))
1688 (dolist (dir (yas--subdirs top-level-dir))
1689 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1690 (concat dir "/dummy")))
1691 (mode-sym (car major-mode-and-parents))
1692 (parents (cdr major-mode-and-parents)))
1693 ;; Attention: The parents and the menus are already defined
1694 ;; here, even if the snippets are later jit-loaded.
1696 ;; * We need to know the parents at this point since entering a
1697 ;; given mode should jit load for its parents
1698 ;; immediately. This could be reviewed, the parents could be
1699 ;; discovered just-in-time-as well
1701 ;; * We need to create the menus here to support the `full'
1702 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1704 (yas--define-parents mode-sym parents)
1705 (yas--menu-keymap-get-create mode-sym)
1706 (let ((form `(yas--load-directory-1 ,dir
1710 (yas--schedule-jit mode-sym form)
1712 (when (interactive-p)
1713 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1715 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1716 "Recursively load snippet templates from DIRECTORY."
1717 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1718 (if (and (not no-compiled-snippets)
1719 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1720 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1721 (yas--message 2 "Loading snippet files from %s" directory)
1722 (yas--load-directory-2 directory mode-sym))))
1724 (defun yas--load-directory-2 (directory mode-sym)
1725 ;; Load .yas-setup.el files wherever we find them
1727 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1728 (let* ((default-directory directory)
1730 ;; load the snippet files
1733 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1734 (when (file-readable-p file)
1735 (insert-file-contents file nil nil nil t)
1736 (push (yas--parse-template file)
1739 (yas-define-snippets mode-sym
1741 ;; now recurse to a lower level
1743 (dolist (subdir (yas--subdirs directory))
1744 (yas--load-directory-2 subdir
1747 (defun yas--load-snippet-dirs (&optional nojit)
1748 "Reload the directories listed in `yas-snippet-dirs' or
1749 prompt the user to select one."
1751 (if yas-snippet-dirs
1752 (dolist (directory (reverse (yas-snippet-dirs)))
1753 (cond ((file-directory-p directory)
1754 (yas-load-directory directory (not nojit))
1756 (yas--message 3 "Loaded %s" directory)
1757 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1759 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1760 (call-interactively 'yas-load-directory))
1763 (defun yas-reload-all (&optional interactive)
1764 "Reload all snippets and rebuild the YASnippet menu.
1766 When called interactively force immediate reload of all known
1767 snippets under `yas-snippet-dirs', otherwise use just-in-time
1772 (snippet-editing-buffers
1773 (remove-if-not #'(lambda (buffer)
1774 (with-current-buffer buffer yas--editing-template))
1776 ;; Warn if there are buffers visiting snippets, since reloading will break
1777 ;; any on-line editing of those buffers.
1779 (when snippet-editing-buffers
1781 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1782 (mapc #'kill-buffer snippet-editing-buffers)
1783 (yas--message 1 "Aborted reload...")
1785 ;; in a non-interactive use, at least set
1786 ;; `yas--editing-template' to nil, make it guess it next time around
1787 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1789 ;; Empty all snippet tables, parenting info and all menu tables
1791 (setq yas--tables (make-hash-table))
1792 (setq yas--parents (make-hash-table))
1793 (setq yas--menu-table (make-hash-table))
1795 ;; Cancel all pending 'yas--scheduled-jit-loads'
1797 (setq yas--scheduled-jit-loads (make-hash-table))
1799 ;; Init the `yas-minor-mode-map', taking care not to break the
1802 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1804 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1805 ;; the user to select one.
1807 (setq errors (yas--load-snippet-dirs interactive))
1808 ;; Reload the direct keybindings
1810 (yas-direct-keymaps-reload)
1811 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1813 (yas--trigger-key-reload)
1815 (yas--message 3 "Reloaded everything%s...%s."
1816 (if interactive "" " (snippets will load just-in-time)")
1817 (if errors " (some errors, check *Messages*)" "")))))
1819 (defun yas--load-pending-jits ()
1820 (when yas-minor-mode
1821 (dolist (mode (yas--modes-to-activate))
1822 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1823 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1824 (dolist (form forms)
1825 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1827 (remhash mode yas--scheduled-jit-loads)))))
1829 ;; (when (<= emacs-major-version 22)
1830 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1832 (defun yas--quote-string (string)
1833 "Escape and quote STRING.
1834 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1836 (replace-regexp-in-string "[\\\"]"
1841 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1842 ;;; Snippet compilation function
1844 (defun yas--initialize ()
1845 "For backward compatibility, enable `yas-minor-mode' globally"
1846 (yas-global-mode 1))
1848 (defun yas-compile-directory (top-level-dir)
1849 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1851 This works by stubbing a few functions, then calling
1852 `yas-load-directory'."
1853 (interactive "DTop level snippet directory?")
1854 (cl-flet ((yas--load-yas-setup-file
1856 (let ((elfile (concat file ".el")))
1857 (when (file-exists-p elfile)
1858 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1859 (insert-file-contents elfile)
1862 (yas-define-snippets
1864 (insert ";;; Snippet definitions:\n;;;\n")
1865 (let ((literal-snippets (list))
1867 (dolist (snippet snippets)
1868 (let ((key (first snippet))
1869 (template-content (second snippet))
1870 (name (third snippet))
1871 (condition (fourth snippet))
1872 (group (fifth snippet))
1873 (expand-env (sixth snippet))
1874 (file nil) ;; (seventh snippet)) ;; omit on purpose
1875 (binding (eighth snippet))
1876 (uuid (ninth snippet)))
1887 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1889 (yas--load-directory-1
1890 (dir mode parents &rest ignore)
1891 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1892 (with-temp-file output-file
1893 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1894 (yas--load-directory-2 dir mode)
1895 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1896 (yas-load-directory top-level-dir nil)))
1898 (defun yas-recompile-all ()
1899 "Compile every dir in `yas-snippet-dirs'."
1901 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1907 (defvar yas--scheduled-jit-loads (make-hash-table)
1908 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1910 (defun yas--schedule-jit (mode form)
1913 (gethash mode yas--scheduled-jit-loads))
1914 yas--scheduled-jit-loads))
1917 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1918 ;;; Some user level functions
1923 (message (concat "yasnippet (version "
1925 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1927 (defun yas--define-parents (mode parents)
1928 "Add PARENTS to the list of MODE's parents"
1929 (puthash mode (remove-duplicates
1931 (gethash mode yas--parents)))
1934 (defun yas-define-snippets (mode snippets)
1935 "Define SNIPPETS for MODE.
1937 SNIPPETS is a list of snippet definitions, each taking the
1940 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1942 Within these, only KEY and TEMPLATE are actually mandatory.
1944 TEMPLATE might be a lisp form or a string, depending on whether
1945 this is a snippet or a snippet-command.
1947 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1948 been `yas--read-lisp'-ed and will eventually be
1949 `yas--eval-lisp'-ed.
1951 The remaining elements are strings.
1953 FILE is probably of very little use if you're programatically
1956 UUID is the snippets \"unique-id\". Loading a second snippet file
1957 with the same uuid replaced the previous snippet.
1959 You can use `yas--parse-template' to return such lists based on
1960 the current buffers contents."
1961 (let ((snippet-table (yas--table-get-create mode))
1963 (dolist (snippet snippets)
1964 (setq template (yas-define-snippets-1 snippet
1968 (defun yas-define-snippets-1 (snippet snippet-table)
1969 "Helper for `yas-define-snippets'."
1970 ;; X) Calculate some more defaults on the values returned by
1971 ;; `yas--parse-template'.
1973 (let* ((file (seventh snippet))
1975 (name (or (third snippet)
1977 (file-name-directory file))))
1978 (condition (fourth snippet))
1979 (group (fifth snippet))
1980 (keybinding (yas--read-keybinding (eighth snippet)))
1981 (uuid (or (ninth snippet)
1983 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1984 (yas--make-blank-template))))
1985 ;; X) populate the template object
1987 (yas--populate-template template
1988 :table snippet-table
1990 :content (second snippet)
1993 :condition condition
1994 :expand-env (sixth snippet)
1995 :file (seventh snippet)
1996 :keybinding keybinding
1998 ;; X) Update this template in the appropriate table. This step
1999 ;; also will take care of adding the key indicators in the
2000 ;; templates menu entry, if any
2002 (yas--update-template snippet-table template)
2003 ;; X) Return the template
2009 ;;; Apropos snippet menu:
2011 ;; The snippet menu keymaps are store by mode in hash table called
2012 ;; `yas--menu-table'. They are linked to the main menu in
2013 ;; `yas--menu-keymap-get-create' and are initially created empty,
2014 ;; reflecting the table hierarchy.
2016 ;; They can be populated in two mutually exclusive ways: (1) by
2017 ;; reading `yas--template-group', which in turn is populated by the "#
2018 ;; group:" directives of the snippets or the ".yas-make-groups" file
2019 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2020 ;; menu structure based on snippets uuids.
2022 ;; Both situations are handled in `yas--update-template-menu', which
2023 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2024 ;; that can tell between the two situations.
2028 ;; * if `yas-define-menu' is used it must run before
2029 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2030 ;; duplicate entries. The `yas--template' objects are created in
2031 ;; `yas-define-menu', holding nothing but the menu entry,
2032 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2033 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2034 ;; part is then stored in the menu keymap itself which make the item
2035 ;; appear to the user. These limitations could probably be revised.
2037 ;; * The `yas--template-perm-group' slot is only used in
2038 ;; `yas-describe-tables'.
2040 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2041 "Get TEMPLATE's menu binding or assign it a new one.
2043 TYPE may be `:stay', signalling this menu binding should be
2044 static in the menu."
2045 (or (yas--template-menu-binding-pair template)
2046 (let ((key (yas--template-key template))
2047 (keybinding (yas--template-keybinding template)))
2048 (setf (yas--template-menu-binding-pair template)
2049 (cons `(menu-item ,(or (yas--template-name template)
2050 (yas--template-uuid template))
2051 ,(yas--make-menu-binding template)
2054 (defun yas--template-menu-managed-by-yas-define-menu (template)
2055 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2056 (cdr (yas--template-menu-binding-pair template)))
2059 (defun yas--show-menu-p (mode)
2060 (cond ((eq yas-use-menu 'abbreviate)
2062 (mapcar #'(lambda (table)
2063 (yas--table-mode table))
2064 (yas--get-snippet-tables))))
2065 ((eq yas-use-menu 'full)
2067 ((eq yas-use-menu t)
2070 (defun yas--delete-from-keymap (keymap uuid)
2071 "Recursively delete items with UUID from KEYMAP and its submenus."
2073 ;; XXX: This used to skip any submenus named \"parent mode\"
2075 ;; First of all, recursively enter submenus, i.e. the tree is
2076 ;; searched depth first so that stale submenus can be found in the
2079 (mapc #'(lambda (item)
2080 (when (and (listp (cdr item))
2081 (keymapp (third (cdr item))))
2082 (yas--delete-from-keymap (third (cdr item)) uuid)))
2084 ;; Set the uuid entry to nil
2086 (define-key keymap (vector (make-symbol uuid)) nil)
2087 ;; Destructively modify keymap
2089 (setcdr keymap (delete-if #'(lambda (item)
2090 (or (null (cdr item))
2091 (and (keymapp (third (cdr item)))
2092 (null (cdr (third (cdr item)))))))
2095 (defun yas-define-menu (mode menu &optional omit-items)
2096 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2098 MENU is a list, its elements can be:
2100 - (yas-item UUID) : Creates an entry the snippet identified with
2101 UUID. The menu entry for a snippet thus identified is
2102 permanent, i.e. it will never move (be reordered) in the menu.
2104 - (yas-separator) : Creates a separator
2106 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2107 SUBMENU has the same form as MENU. NAME is also added to the
2108 list of groups of the snippets defined thereafter.
2110 OMIT-ITEMS is a list of snippet uuid's that will always be
2111 ommited from MODE's menu, even if they're manually loaded.
2113 This function does nothing if `yas-use-menu' is nil.
2116 (let* ((table (yas--table-get-create mode))
2117 (hash (yas--table-uuidhash table)))
2118 (yas--define-menu-1 table
2119 (yas--menu-keymap-get-create mode)
2122 (dolist (uuid omit-items)
2123 (let ((template (or (gethash uuid hash)
2124 (yas--populate-template (puthash uuid
2125 (yas--make-blank-template)
2129 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2131 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2132 (dolist (e (reverse menu))
2133 (cond ((eq (first e) 'yas-item)
2134 (let ((template (or (gethash (second e) uuidhash)
2135 (yas--populate-template (puthash (second e)
2136 (yas--make-blank-template)
2139 :perm-group group-list
2140 :uuid (second e)))))
2141 (define-key menu-keymap (vector (gensym))
2142 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2143 ((eq (first e) 'yas-submenu)
2144 (let ((subkeymap (make-sparse-keymap)))
2145 (define-key menu-keymap (vector (gensym))
2146 `(menu-item ,(second e) ,subkeymap))
2147 (yas--define-menu-1 table
2151 (append group-list (list (second e))))))
2152 ((eq (first e) 'yas-separator)
2153 (define-key menu-keymap (vector (gensym))
2154 '(menu-item "----")))
2156 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2158 (defun yas--define (mode key template &optional name condition group)
2159 "Define a snippet. Expanding KEY into TEMPLATE.
2161 NAME is a description to this template. Also update the menu if
2162 `yas-use-menu' is t. CONDITION is the condition attached to
2163 this snippet. If you attach a condition to a snippet, then it
2164 will only be expanded when the condition evaluated to non-nil."
2165 (yas-define-snippets mode
2166 (list (list key template name condition group))))
2168 (defun yas-hippie-try-expand (first-time?)
2169 "Integrate with hippie expand. Just put this function in
2170 `hippie-expand-try-functions-list'."
2171 (when yas-minor-mode
2172 (if (not first-time?)
2173 (let ((yas-fallback-behavior 'return-nil))
2179 ;;; Apropos condition-cache:
2184 (defvar yas--condition-cache-timestamp nil)
2185 (defmacro yas-define-condition-cache (func doc &rest body)
2186 "Define a function FUNC with doc DOC and body BODY, BODY is
2187 executed at most once every snippet expansion attempt, to check
2188 expansion conditions.
2190 It doesn't make any sense to call FUNC programatically."
2191 `(defun ,func () ,(if (and doc
2194 "\n\nFor use in snippets' conditions. Within each
2195 snippet-expansion routine like `yas-expand', computes actual
2196 value for the first time then always returns a cached value.")
2197 (setq body (cons doc body))
2199 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2200 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2201 (cdr timestamp-and-value)
2202 (let ((new-value (progn
2205 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2208 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2209 (defun yas-expand-from-trigger-key (&optional field)
2210 "Expand a snippet before point.
2212 If no snippet expansion is possible, fall back to the behaviour
2213 defined in `yas-fallback-behavior'.
2215 Optional argument FIELD is for non-interactive use and is an
2216 object satisfying `yas--field-p' to restrict the expansion to."
2218 (setq yas--condition-cache-timestamp (current-time))
2219 (let (templates-and-pos)
2220 (unless (and yas-expand-only-for-last-commands
2221 (not (member last-command yas-expand-only-for-last-commands)))
2222 (setq templates-and-pos (if field
2224 (narrow-to-region (yas--field-start field)
2225 (yas--field-end field))
2227 (yas--current-key))))
2228 (if (and templates-and-pos
2229 (first templates-and-pos))
2230 (yas--expand-or-prompt-for-template (first templates-and-pos)
2231 (second templates-and-pos)
2232 (third templates-and-pos))
2233 (yas--fallback 'trigger-key))))
2235 (defun yas-expand-from-keymap ()
2236 "Directly expand some snippets, searching `yas--direct-keymaps'.
2238 If expansion fails, execute the previous binding for this key"
2240 (setq yas--condition-cache-timestamp (current-time))
2241 (let* ((yas--prefix current-prefix-arg)
2242 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2243 universal-argument-num-events
2245 (templates (mapcan #'(lambda (table)
2246 (yas--fetch table vec))
2247 (yas--get-snippet-tables))))
2249 (yas--expand-or-prompt-for-template templates)
2250 (let ((yas-fallback-behavior 'call-other-command))
2253 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2254 "Expand one of TEMPLATES from START to END.
2256 Prompt the user if TEMPLATES has more than one element, else
2257 expand immediately. Common gateway for
2258 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2259 (let ((yas--current-template (or (and (rest templates) ;; more than one
2260 (yas--prompt-for-template (mapcar #'cdr templates)))
2262 (when yas--current-template
2263 (yas-expand-snippet (yas--template-content yas--current-template)
2266 (yas--template-expand-env yas--current-template)))))
2268 (defun yas--trigger-key-for-fallback ()
2269 ;; When `yas-trigger-key' is <tab> it correctly overrides
2270 ;; org-mode's <tab>, for example and searching for fallbacks
2271 ;; correctly returns `org-cycle'. However, most other modes bind
2272 ;; "TAB" (which is translated from <tab>), and calling
2273 ;; (key-binding "TAB") does not place return that command into
2274 ;; our command-2 local. So we cheat.
2276 (if (string= yas-trigger-key "<tab>")
2280 (defun yas--fallback (&optional from-trigger-key-p)
2281 "Fallback after expansion has failed.
2283 Common gateway for `yas-expand-from-trigger-key' and
2284 `yas-expand-from-keymap'."
2285 (cond ((eq yas-fallback-behavior 'return-nil)
2288 ((eq yas-fallback-behavior 'call-other-command)
2289 (let* ((yas-minor-mode nil)
2290 (yas--direct-keymaps nil)
2291 (yas-trigger-key (yas--trigger-key-for-fallback))
2292 (keys-1 (this-command-keys-vector))
2293 (keys-2 (and yas-trigger-key
2295 (stringp yas-trigger-key)
2296 (read-kbd-macro yas-trigger-key)))
2297 (command-1 (and keys-1 (key-binding keys-1)))
2298 (command-2 (and keys-2 (key-binding keys-2)))
2299 ;; An (ugly) safety: prevents infinite recursion of
2300 ;; yas-expand* calls.
2301 (command (or (and (symbolp command-1)
2302 (not (string-match "yas-expand" (symbol-name command-1)))
2304 (and (symbolp command-2)
2306 (when (and (commandp command)
2307 (not (string-match "yas-expand" (symbol-name command))))
2308 (setq this-command command)
2309 (call-interactively command))))
2310 ((and (listp yas-fallback-behavior)
2311 (cdr yas-fallback-behavior)
2312 (eq 'apply (car yas-fallback-behavior)))
2313 (if (cddr yas-fallback-behavior)
2314 (apply (cadr yas-fallback-behavior)
2315 (cddr yas-fallback-behavior))
2316 (when (commandp (cadr yas-fallback-behavior))
2317 (setq this-command (cadr yas-fallback-behavior))
2318 (call-interactively (cadr yas-fallback-behavior)))))
2320 ;; also return nil if all the other fallbacks have failed
2325 ;;; Utils for snippet development:
2327 (defun yas--all-templates (tables)
2328 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2330 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2331 `yas-buffer-local-condition'"
2332 (when yas-choose-tables-first
2333 (setq tables (list (yas--prompt-for-table tables))))
2335 (if yas-choose-keys-first
2336 (let ((key (yas--prompt-for-keys
2337 (mapcan #'yas--table-all-keys tables))))
2339 (mapcan #'(lambda (table)
2340 (yas--fetch table key))
2342 (remove-duplicates (mapcan #'yas--table-templates tables)
2345 (defun yas-insert-snippet (&optional no-condition)
2346 "Choose a snippet to expand, pop-up a list of choices according
2347 to `yas--prompt-function'.
2349 With prefix argument NO-CONDITION, bypass filtering of snippets
2352 (setq yas--condition-cache-timestamp (current-time))
2353 (let* ((yas-buffer-local-condition (or (and no-condition
2355 yas-buffer-local-condition))
2356 (templates (yas--all-templates (yas--get-snippet-tables)))
2357 (yas--current-template (and templates
2358 (or (and (rest templates) ;; more than one template for same key
2359 (yas--prompt-for-template templates))
2361 (where (if (region-active-p)
2362 (cons (region-beginning) (region-end))
2363 (cons (point) (point)))))
2364 (if yas--current-template
2365 (yas-expand-snippet (yas--template-content yas--current-template)
2368 (yas--template-expand-env yas--current-template))
2369 (yas--message 3 "No snippets can be inserted here!"))))
2371 (defun yas-visit-snippet-file ()
2372 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2374 Only success if selected snippet was loaded from a file. Put the
2375 visited file in `snippet-mode'."
2377 (let* ((yas-buffer-local-condition 'always)
2378 (templates (yas--all-templates (yas--get-snippet-tables)))
2379 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2380 (template (and templates
2381 (or (yas--prompt-for-template templates
2382 "Choose a snippet template to edit: ")
2386 (yas--visit-snippet-file-1 template)
2387 (message "No snippets tables active!"))))
2389 (defun yas--visit-snippet-file-1 (template)
2390 (let ((file (yas--template-file template)))
2391 (cond ((and file (file-readable-p file))
2392 (find-file-other-window file)
2394 (set (make-local-variable 'yas--editing-template) template))
2396 (message "Original file %s no longer exists!" file))
2398 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2399 (let ((type 'snippet))
2400 (when (listp (yas--template-content template))
2401 (insert (format "# type: command\n"))
2402 (setq type 'command))
2403 (insert (format "# key: %s\n" (yas--template-key template)))
2404 (insert (format "# name: %s\n" (yas--template-name template)))
2405 (when (yas--template-keybinding template)
2406 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2407 (when (yas--template-expand-env template)
2408 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2409 (when (yas--template-condition template)
2410 (insert (format "# condition: %s\n" (yas--template-condition template))))
2412 (insert (if (eq type 'command)
2413 (pp-to-string (yas--template-content template))
2414 (yas--template-content template))))
2416 (set (make-local-variable 'yas--editing-template) template)))))
2418 (defun yas--guess-snippet-directories-1 (table)
2419 "Guesses possible snippet subdirectories for TABLE."
2420 (cons (yas--table-name table)
2421 (mapcan #'(lambda (parent)
2422 (yas--guess-snippet-directories-1
2424 (yas--table-parents table))))
2426 (defun yas--guess-snippet-directories (&optional table)
2427 "Try to guess suitable directories based on the current active
2428 tables (or optional TABLE).
2430 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2431 `yas--table' object and DIRS is a list of all possible directories
2432 where snippets of table might exist."
2433 (let ((main-dir (replace-regexp-in-string
2435 (or (first (or (yas-snippet-dirs)
2436 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2437 (tables (or (and table
2439 (yas--get-snippet-tables))))
2440 ;; HACK! the snippet table created here is actually registered!
2442 (unless (or table (gethash major-mode yas--tables))
2443 (push (yas--table-get-create major-mode)
2446 (mapcar #'(lambda (table)
2448 (mapcar #'(lambda (subdir)
2449 (concat main-dir "/" subdir))
2450 (yas--guess-snippet-directories-1 table))))
2453 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2454 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2455 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2456 (let ((candidate (first (cdr table-and-dirs))))
2457 (unless (file-writable-p (file-name-directory candidate))
2458 (error (yas--format "%s is not writable." candidate)))
2459 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2461 (if (gethash (yas--table-mode (car table-and-dirs))
2465 (or main-table-string
2467 (yas--table-name (car table-and-dirs))))
2469 (make-directory candidate 'also-make-parents)
2470 ;; create the .yas-parents file here...
2473 (defun yas-new-snippet (&optional no-template)
2474 "Pops a new buffer for writing a snippet.
2476 Expands a snippet-writing snippet, unless the optional prefix arg
2477 NO-TEMPLATE is non-nil."
2479 (let ((guessed-directories (yas--guess-snippet-directories)))
2481 (switch-to-buffer "*new snippet*")
2483 (kill-all-local-variables)
2486 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2487 (yas--table-mode (car d)))
2488 guessed-directories))
2489 (unless no-template (yas-expand-snippet "\
2490 # -*- mode: snippet -*-
2492 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2493 # binding: ${4:direct-keybinding}}${5:
2494 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2499 (defun yas--compute-major-mode-and-parents (file)
2500 "Given FILE, find the nearest snippet directory for a given
2501 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2502 representing one or more of the mode's parents.
2504 Note that MODE-SYM need not be the symbol of a real major mode,
2505 neither do the elements of PARENTS."
2506 (let* ((file-dir (and file
2507 (directory-file-name (or (some #'(lambda (special)
2508 (locate-dominating-file file special))
2512 (directory-file-name (file-name-directory file))))))
2513 (parents-file-name (concat file-dir "/.yas-parents"))
2514 (major-mode-name (and file-dir
2515 (file-name-nondirectory file-dir)))
2516 (major-mode-sym (or (and major-mode-name
2517 (intern major-mode-name))))
2518 (parents (when (file-readable-p parents-file-name)
2522 (insert-file-contents parents-file-name)
2523 (buffer-substring-no-properties (point-min)
2525 (when major-mode-sym
2526 (cons major-mode-sym parents))))
2528 (defvar yas--editing-template nil
2529 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'")
2531 (defvar yas--current-template nil
2532 "Holds the current template being expanded into a snippet.")
2534 (defvar yas--guessed-modes nil
2535 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2537 (defun yas--read-table ()
2538 "Ask user for a snippet table, help with some guessing."
2539 (let ((prompt (if (and (featurep 'ido)
2541 'ido-completing-read 'completing-read)))
2542 (unless yas--guessed-modes
2543 (set (make-local-variable 'yas--guessed-modes)
2544 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2546 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2547 (if yas--guessed-modes
2548 (first yas--guessed-modes)
2550 (mapcar #'symbol-name yas--guessed-modes)
2555 (if (first yas--guessed-modes)
2556 (symbol-name (first yas--guessed-modes)))))))
2558 (defun yas-load-snippet-buffer (table &optional interactive)
2559 "Parse and load current buffer's snippet definition into TABLE.
2561 TABLE is a symbol naming a passed to `yas--table-get-create'.
2563 When called interactively, prompt for the table name and
2564 whether (and where) to save the snippet, then quit the window."
2565 (interactive (list (yas--read-table) t))
2567 ;; We have `yas--editing-template', this buffer's content comes from a
2568 ;; template which is already loaded and neatly positioned,...
2570 (yas--editing-template
2571 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2572 (yas--template-table yas--editing-template)))
2573 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2574 ;; value from `yas--compute-major-mode-and-parents'
2577 (unless yas--guessed-modes
2578 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2579 (let* ((table (yas--table-get-create table)))
2580 (set (make-local-variable 'yas--editing-template)
2581 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2584 (when (and interactive
2586 ;; Only offer to save this if it looks like a library or new
2587 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2588 ;; which is not the first, or from an unwritable file)
2590 (not (yas--template-file yas--editing-template))
2591 (not (file-writable-p (yas--template-file yas--editing-template)))
2592 (and (listp yas-snippet-dirs)
2593 (second yas-snippet-dirs)
2594 (not (string-match (expand-file-name (first yas-snippet-dirs))
2595 (yas--template-file yas--editing-template)))))
2596 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2597 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2599 (yas--make-directory-maybe option))))
2601 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2602 (file-name-nondirectory (yas--template-file yas--editing-template)))
2603 (yas--template-name yas--editing-template))))
2604 (write-file (concat chosen "/"
2605 (read-from-minibuffer (format "File name to create in %s? " chosen)
2606 default-file-name)))
2607 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2609 (yas--message 3 "Snippet \"%s\" loaded for %s."
2610 (yas--template-name yas--editing-template)
2611 (yas--table-name (yas--template-table yas--editing-template)))
2612 (quit-window interactive)))
2614 (defun yas-tryout-snippet (&optional debug)
2615 "Test current buffers's snippet template in other buffer."
2617 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2618 (parsed (yas--parse-template))
2619 (test-mode (or (and (car major-mode-and-parent)
2620 (fboundp (car major-mode-and-parent))
2621 (car major-mode-and-parent))
2622 (first yas--guessed-modes)
2623 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2624 (yas--current-template
2627 (yas--populate-template (yas--make-blank-template)
2628 :table nil ;; no tables for ephemeral snippets
2630 :content (second parsed)
2631 :name (third parsed)
2632 :expand-env (sixth parsed)))))
2633 (cond (yas--current-template
2634 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2635 (kill-buffer (get-buffer-create buffer-name))
2636 (switch-to-buffer (get-buffer-create buffer-name))
2637 (setq buffer-undo-list nil)
2638 (condition-case nil (funcall test-mode) (error nil))
2640 (setq buffer-read-only nil)
2641 (yas-expand-snippet (yas--template-content yas--current-template)
2644 (yas--template-expand-env yas--current-template))
2646 (require 'yasnippet-debug nil t))
2647 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2649 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2651 (defun yas-active-keys ()
2652 "Return all active trigger keys for current buffer and point"
2653 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2656 (defun yas--template-fine-group (template)
2657 (car (last (or (yas--template-group template)
2658 (yas--template-perm-group template)))))
2660 (defun yas-describe-tables (&optional choose)
2661 "Display snippets for each table."
2663 (let* ((by-name-hash (and choose
2664 (y-or-n-p "Show by namehash? ")))
2665 (buffer (get-buffer-create "*YASnippet tables*"))
2666 (active-tables (yas--get-snippet-tables))
2667 (remain-tables (let ((all))
2668 (maphash #'(lambda (k v)
2669 (unless (find v active-tables)
2673 (table-lists (list active-tables remain-tables))
2674 (original-buffer (current-buffer))
2676 (yas--condition-cache-timestamp (current-time)))
2677 (with-current-buffer buffer
2678 (setq buffer-read-only nil)
2680 (cond ((not by-name-hash)
2681 (insert "YASnippet tables: \n")
2682 (while (and table-lists
2684 (dolist (table (car table-lists))
2685 (yas--describe-pretty-table table original-buffer))
2686 (setq table-lists (cdr table-lists))
2688 (yas--create-snippet-xrefs)
2689 (display-buffer buffer)
2690 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2691 (yas--create-snippet-xrefs)
2695 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2696 (dolist (table (append active-tables remain-tables))
2697 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2699 (maphash #'(lambda (k v)
2701 (yas--table-hash table))
2703 (insert (format " key %s maps snippets: %s\n" key
2705 (maphash #'(lambda (k v)
2707 (gethash key (yas--table-hash table)))
2710 (setq buffer-read-only t))
2711 (display-buffer buffer)))
2713 (defun yas--describe-pretty-table (table &optional original-buffer)
2714 (insert (format "\nSnippet table `%s'"
2715 (yas--table-name table)))
2716 (if (yas--table-parents table)
2717 (insert (format " parents: %s\n"
2718 (mapcar #'yas--table-name
2719 (yas--table-parents table))))
2721 (insert (make-string 100 ?-) "\n")
2722 (insert "group state name key binding\n")
2723 (let ((groups-hash (make-hash-table :test #'equal)))
2724 (maphash #'(lambda (k v)
2725 (let ((group (or (yas--template-fine-group v)
2727 (when (yas--template-name v)
2729 (cons v (gethash group groups-hash))
2731 (yas--table-uuidhash table))
2733 #'(lambda (group templates)
2734 (setq group (truncate-string-to-width group 25 0 ? "..."))
2735 (insert (make-string 100 ?-) "\n")
2736 (dolist (p templates)
2737 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2741 (setq group (make-string (length group) ? ))))
2742 (condition-string (let ((condition (yas--template-condition p)))
2745 (with-current-buffer original-buffer
2746 (if (yas--eval-condition condition)
2751 (insert condition-string " ")
2753 (if (string-match "\\.\\.\\.$" name)
2757 (insert (truncate-string-to-width (or (yas--template-key p) "")
2759 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2766 ;;; User convenience functions, for using in snippet definitions
2768 (defvar yas-modified-p nil
2769 "Non-nil if field has been modified by user or transformation.")
2771 (defvar yas-moving-away-p nil
2772 "Non-nil if user is about to exit field.")
2774 (defvar yas-text nil
2775 "Contains current field text.")
2777 (defun yas-substr (str pattern &optional subexp)
2778 "Search PATTERN in STR and return SUBEXPth match.
2780 If found, the content of subexp group SUBEXP (default 0) is
2781 returned, or else the original STR will be returned."
2782 (let ((grp (or subexp 0)))
2784 (if (string-match pattern str)
2785 (match-string-no-properties grp str)
2788 (defun yas-choose-value (&rest possibilities)
2789 "Prompt for a string in POSSIBILITIES and return it.
2791 The last element of POSSIBILITIES may be a list of strings."
2792 (unless (or yas-moving-away-p
2794 (setq possibilities (nreverse possibilities))
2795 (setq possibilities (if (listp (car possibilities))
2796 (append (reverse (car possibilities)) (rest possibilities))
2798 (some #'(lambda (fn)
2799 (funcall fn "Choose: " possibilities))
2800 yas-prompt-functions)))
2802 (defun yas-key-to-value (alist)
2803 "Prompt for a string in the list POSSIBILITIES and return it."
2804 (unless (or yas-moving-away-p
2806 (let ((key (read-key-sequence "")))
2808 (or (cdr (find key alist :key #'car :test #'string=))
2811 (defun yas-throw (text)
2812 "Throw a yas--exception with TEXT as the reason."
2813 (throw 'yas--exception (cons 'yas--exception text)))
2815 (defun yas-verify-value (possibilities)
2816 "Verify that the current field value is in POSSIBILITIES
2818 Otherwise throw exception."
2819 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2820 (yas-throw (yas--format "Field only allows %s" possibilities))))
2822 (defun yas-field-value (number)
2823 "Get the string for field with NUMBER.
2825 Use this in primary and mirror transformations to tget."
2826 (let* ((snippet (car (yas--snippets-at-point)))
2828 (yas--snippet-find-field snippet number))))
2830 (yas--field-text-for-display field))))
2833 "Return `yas-text' if that exists and is non-empty, else nil."
2835 (not (string= "" yas-text)))
2838 (defun yas-selected-text ()
2839 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2840 (if (and yas-selected-text
2841 (not (string= "" yas-selected-text)))
2844 (defun yas--get-field-once (number &optional transform-fn)
2845 (unless yas-modified-p
2847 (funcall transform-fn (yas-field-value number))
2848 (yas-field-value number))))
2850 (defun yas-default-from-field (number)
2851 (unless yas-modified-p
2852 (yas-field-value number)))
2854 (defun yas-inside-string ()
2855 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2857 (defun yas-unimplemented (&optional missing-feature)
2858 (if yas--current-template
2859 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2862 (yas--visit-snippet-file-1 yas--current-template))
2863 (message "No implementation. Missing %s" (or missing-feature "something"))))
2866 ;;; Snippet expansion and field management
2868 (defvar yas--active-field-overlay nil
2869 "Overlays the currently active field.")
2871 (defvar yas--field-protection-overlays nil
2872 "Two overlays protect the current active field ")
2874 (defconst yas--prefix nil
2875 "A prefix argument for expansion direct from keybindings")
2877 (defvar yas-selected-text nil
2878 "The selected region deleted on the last snippet expansion.")
2880 (defvar yas--start-column nil
2881 "The column where the snippet expansion started.")
2883 (make-variable-buffer-local 'yas--active-field-overlay)
2884 (make-variable-buffer-local 'yas--field-protection-overlays)
2885 (put 'yas--active-field-overlay 'permanent-local t)
2886 (put 'yas--field-protection-overlays 'permanent-local t)
2888 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2894 (id (yas--snippet-next-id) :read-only t)
2895 (control-overlay nil)
2897 ;; stacked expansion: the `previous-active-field' slot saves the
2898 ;; active field where the child expansion took place
2899 previous-active-field
2902 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2912 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2919 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2923 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2924 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2926 If there is no transform for ht field, return nil.
2928 If there is a transform but it returns nil, return the empty
2929 string iff EMPTY-ON-NIL-P is true."
2930 (let* ((yas-text (yas--field-text-for-display field))
2932 (yas-modified-p (yas--field-modified-p field))
2933 (yas-moving-away-p nil)
2934 (transform (if (yas--mirror-p field-or-mirror)
2935 (yas--mirror-transform field-or-mirror)
2936 (yas--field-transform field-or-mirror)))
2937 (start-point (if (yas--mirror-p field-or-mirror)
2938 (yas--mirror-start field-or-mirror)
2939 (yas--field-start field-or-mirror)))
2940 (transformed (and transform
2942 (goto-char start-point)
2943 (let ((ret (yas--eval-lisp transform)))
2944 (or ret (and empty-on-nil-p "")))))))
2947 (defsubst yas--replace-all (from to &optional text)
2948 "Replace all occurance from FROM to TO.
2950 With optional string TEXT do it in that string."
2952 (replace-regexp-in-string (regexp-quote from) to text t t)
2953 (goto-char (point-min))
2954 (while (search-forward from nil t)
2955 (replace-match to t t text))))
2957 (defun yas--snippet-find-field (snippet number)
2958 (find-if #'(lambda (field)
2959 (eq number (yas--field-number field)))
2960 (yas--snippet-fields snippet)))
2962 (defun yas--snippet-sort-fields (snippet)
2963 "Sort the fields of SNIPPET in navigation order."
2964 (setf (yas--snippet-fields snippet)
2965 (sort (yas--snippet-fields snippet)
2966 #'yas--snippet-field-compare)))
2968 (defun yas--snippet-field-compare (field1 field2)
2969 "Compare two fields. The field with a number is sorted first.
2970 If they both have a number, compare through the number. If neither
2971 have, compare through the field's start point"
2972 (let ((n1 (yas--field-number field1))
2973 (n2 (yas--field-number field2)))
2976 (or (zerop n2) (and (not (zerop n1))
2981 (< (yas--field-start field1)
2982 (yas--field-start field2))))))
2984 (defun yas--field-probably-deleted-p (snippet field)
2985 "Guess if SNIPPET's FIELD should be skipped."
2987 ;; field must be zero lentgh
2989 (zerop (- (yas--field-start field) (yas--field-end field)))
2992 ;; 1) is a nested field and it's been modified
2994 (and (yas--field-parent-field field)
2995 (yas--field-modified-p field))
2996 ;; 2) ends just before the snippet end
2998 (and (eq field (car (last (yas--snippet-fields snippet))))
2999 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3000 ;; the field numbered 0, just before the exit marker, should
3003 (not (zerop (yas--field-number field)))))
3005 (defun yas--snippets-at-point (&optional all-snippets)
3006 "Return a sorted list of snippets at point, most recently
3009 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3010 (overlay-get ov 'yas--snippet))
3012 (overlays-in (point-min) (point-max))
3013 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3015 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3017 (defun yas-next-field-or-maybe-expand ()
3018 "Try to expand a snippet at a key before point, otherwise
3019 delegate to `yas-next-field'."
3021 (if yas-triggers-in-field
3022 (let ((yas-fallback-behavior 'return-nil)
3023 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3025 (unless (yas-expand-from-trigger-key active-field)
3029 (defun yas-next-field (&optional arg)
3030 "Navigate to next field. If there's none, exit the snippet."
3034 (snippet (first (yas--snippets-at-point)))
3035 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3036 (live-fields (remove-if #'(lambda (field)
3037 (and (not (eq field active-field))
3038 (yas--field-probably-deleted-p snippet field)))
3039 (yas--snippet-fields snippet)))
3040 (active-field-pos (position active-field live-fields))
3041 (target-pos (and active-field-pos (+ arg active-field-pos)))
3042 (target-field (and target-pos (nth target-pos live-fields))))
3043 ;; First check if we're moving out of a field with a transform
3045 (when (and active-field
3046 (yas--field-transform active-field))
3047 (let* ((yas-moving-away-p t)
3048 (yas-text (yas--field-text-for-display active-field))
3050 (yas-modified-p (yas--field-modified-p active-field)))
3051 ;; primary field transform: exit call to field-transform
3052 (yas--eval-lisp (yas--field-transform active-field))))
3053 ;; Now actually move...
3054 (cond ((and target-pos (>= target-pos (length live-fields)))
3055 (yas-exit-snippet snippet))
3057 (yas--move-to-field snippet target-field))
3061 (defun yas--place-overlays (snippet field)
3062 "Correctly place overlays for SNIPPET's FIELD"
3063 (yas--make-move-field-protection-overlays snippet field)
3064 (yas--make-move-active-field-overlay snippet field))
3066 (defun yas--move-to-field (snippet field)
3067 "Update SNIPPET to move to field FIELD.
3069 Also create some protection overlays"
3070 (goto-char (yas--field-start field))
3071 (yas--place-overlays snippet field)
3072 (overlay-put yas--active-field-overlay 'yas--field field)
3073 (let ((number (yas--field-number field)))
3074 ;; check for the special ${0: ...} field
3075 (if (and number (zerop number))
3077 (set-mark (yas--field-end field))
3078 (setf (yas--snippet-force-exit snippet)
3079 (or (yas--field-transform field)
3081 ;; make this field active
3082 (setf (yas--snippet-active-field snippet) field)
3083 ;; primary field transform: first call to snippet transform
3084 (unless (yas--field-modified-p field)
3085 (if (yas--field-update-display field snippet)
3086 (yas--update-mirrors snippet)
3087 (setf (yas--field-modified-p field) nil))))))
3089 (defun yas-prev-field ()
3090 "Navigate to prev field. If there's none, exit the snippet."
3092 (yas-next-field -1))
3094 (defun yas-abort-snippet (&optional snippet)
3096 (let ((snippet (or snippet
3097 (car (yas--snippets-at-point)))))
3099 (setf (yas--snippet-force-exit snippet) t))))
3101 (defun yas-exit-snippet (snippet)
3102 "Goto exit-marker of SNIPPET."
3103 (interactive (list (first (yas--snippets-at-point))))
3105 (setf (yas--snippet-force-exit snippet) t)
3106 (goto-char (if (yas--snippet-exit snippet)
3107 (yas--exit-marker (yas--snippet-exit snippet))
3108 (overlay-end (yas--snippet-control-overlay snippet))))))
3110 (defun yas-exit-all-snippets ()
3111 "Exit all snippets."
3113 (mapc #'(lambda (snippet)
3114 (yas-exit-snippet snippet)
3115 (yas--check-commit-snippet))
3116 (yas--snippets-at-point 'all-snippets)))
3119 ;;; Some low level snippet-routines:
3121 (defmacro yas--inhibit-overlay-hooks (&rest body)
3122 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3123 (declare (indent 0))
3124 `(let ((yas--inhibit-overlay-hooks t))
3127 (defvar yas-snippet-beg nil "Beginning position of the last snippet commited.")
3128 (defvar yas-snippet-end nil "End position of the last snippet commited.")
3130 (defun yas--commit-snippet (snippet)
3131 "Commit SNIPPET, but leave point as it is. This renders the
3132 snippet as ordinary text."
3134 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3136 ;; Save the end of the moribund snippet in case we need to revive it
3137 ;; its original expansion.
3139 (when (and control-overlay
3140 (overlay-buffer control-overlay))
3141 (setq yas-snippet-beg (overlay-start control-overlay))
3142 (setq yas-snippet-end (overlay-end control-overlay))
3143 (delete-overlay control-overlay))
3145 (yas--inhibit-overlay-hooks
3146 (when yas--active-field-overlay
3147 (delete-overlay yas--active-field-overlay))
3148 (when yas--field-protection-overlays
3149 (mapc #'delete-overlay yas--field-protection-overlays)))
3151 ;; stacked expansion: if the original expansion took place from a
3152 ;; field, make sure we advance it here at least to
3153 ;; `yas-snippet-end'...
3155 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3156 (when (and yas-snippet-end previous-field)
3157 (yas--advance-end-maybe previous-field yas-snippet-end)))
3159 ;; Convert all markers to points,
3161 (yas--markers-to-points snippet)
3163 ;; Take care of snippet revival
3165 (if yas-snippet-revival
3166 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3168 ;; Dismember the snippet... this is useful if we get called
3169 ;; again from `yas--take-care-of-redo'....
3170 (setf (yas--snippet-fields snippet) nil)))
3172 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3174 (defun yas--safely-run-hooks (hook-var)
3175 (condition-case error
3176 (run-hooks hook-var)
3178 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3181 (defun yas--check-commit-snippet ()
3182 "Checks if point exited the currently active field of the
3183 snippet, if so cleans up the whole snippet up."
3184 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3185 (snippets-left snippets)
3186 (snippet-exit-transform))
3187 (dolist (snippet snippets)
3188 (let ((active-field (yas--snippet-active-field snippet)))
3189 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3190 (cond ((or snippet-exit-transform
3191 (not (and active-field (yas--field-contains-point-p active-field))))
3192 (setq snippets-left (delete snippet snippets-left))
3193 (setf (yas--snippet-force-exit snippet) nil)
3194 (yas--commit-snippet snippet))
3196 (or (not yas--active-field-overlay)
3197 (not (overlay-buffer yas--active-field-overlay))))
3199 ;; stacked expansion: this case is mainly for recent
3200 ;; snippet exits that place us back int the field of
3204 (yas--move-to-field snippet active-field)
3205 (yas--update-mirrors snippet)))
3208 (unless (or (null snippets) snippets-left)
3209 (if snippet-exit-transform
3210 (yas--eval-lisp-no-saves snippet-exit-transform))
3211 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3213 ;; Apropos markers-to-points:
3215 ;; This was found useful for performance reasons, so that an
3216 ;; excessive number of live markers aren't kept around in the
3217 ;; `buffer-undo-list'. However, in `markers-to-points', the
3218 ;; set-to-nil markers can't simply be discarded and replaced with
3219 ;; fresh ones in `points-to-markers'. The original marker that was
3220 ;; just set to nil has to be reused.
3222 ;; This shouldn't bring horrible problems with undo/redo, but it
3225 (defun yas--markers-to-points (snippet)
3226 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3227 where POINT is the original position of the marker and MARKER is
3228 the original marker object with the position set to nil."
3229 (dolist (field (yas--snippet-fields snippet))
3230 (let ((start (marker-position (yas--field-start field)))
3231 (end (marker-position (yas--field-end field))))
3232 (set-marker (yas--field-start field) nil)
3233 (set-marker (yas--field-end field) nil)
3234 (setf (yas--field-start field) (cons start (yas--field-start field)))
3235 (setf (yas--field-end field) (cons end (yas--field-end field))))
3236 (dolist (mirror (yas--field-mirrors field))
3237 (let ((start (marker-position (yas--mirror-start mirror)))
3238 (end (marker-position (yas--mirror-end mirror))))
3239 (set-marker (yas--mirror-start mirror) nil)
3240 (set-marker (yas--mirror-end mirror) nil)
3241 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3242 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3243 (let ((snippet-exit (yas--snippet-exit snippet)))
3245 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3246 (set-marker (yas--exit-marker snippet-exit) nil)
3247 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3249 (defun yas--points-to-markers (snippet)
3250 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3251 is done by setting MARKER to POINT with `set-marker'."
3252 (dolist (field (yas--snippet-fields snippet))
3253 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3254 (car (yas--field-start field))))
3255 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3256 (car (yas--field-end field))))
3257 (dolist (mirror (yas--field-mirrors field))
3258 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3259 (car (yas--mirror-start mirror))))
3260 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3261 (car (yas--mirror-end mirror))))))
3262 (let ((snippet-exit (yas--snippet-exit snippet)))
3264 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3265 (car (yas--exit-marker snippet-exit)))))))
3267 (defun yas--field-contains-point-p (field &optional point)
3268 (let ((point (or point
3270 (and (>= point (yas--field-start field))
3271 (<= point (yas--field-end field)))))
3273 (defun yas--field-text-for-display (field)
3274 "Return the propertized display text for field FIELD. "
3275 (buffer-substring (yas--field-start field) (yas--field-end field)))
3277 (defun yas--undo-in-progress ()
3278 "True if some kind of undo is in progress"
3279 (or undo-in-progress
3280 (eq this-command 'undo)
3281 (eq this-command 'redo)))
3283 (defun yas--make-control-overlay (snippet start end)
3284 "Creates the control overlay that surrounds the snippet and
3286 (let ((overlay (make-overlay start
3291 (overlay-put overlay 'keymap yas-keymap)
3292 (overlay-put overlay 'priority 100)
3293 (overlay-put overlay 'yas--snippet snippet)
3296 (defun yas-skip-and-clear-or-delete-char (&optional field)
3297 "Clears unmodified field if at field start, skips to next tab.
3299 Otherwise deletes a character normally by calling `delete-char'."
3301 (let ((field (or field
3302 (and yas--active-field-overlay
3303 (overlay-buffer yas--active-field-overlay)
3304 (overlay-get yas--active-field-overlay 'yas--field)))))
3306 (not (yas--field-modified-p field))
3307 (eq (point) (marker-position (yas--field-start field))))
3308 (yas--skip-and-clear field)
3311 (call-interactively 'delete-char)))))
3313 (defun yas--skip-and-clear (field)
3314 "Deletes the region of FIELD and sets it modified state to t"
3315 ;; Just before skipping-and-clearing the field, mark its children
3316 ;; fields as modified, too. If the childen have mirrors-in-fields
3317 ;; this prevents them from updating erroneously (we're skipping and
3320 (yas--mark-this-and-children-modified field)
3321 (delete-region (yas--field-start field) (yas--field-end field)))
3323 (defun yas--mark-this-and-children-modified (field)
3324 (setf (yas--field-modified-p field) t)
3325 (let ((fom (yas--field-next field)))
3327 (yas--fom-parent-field fom))
3328 (when (and (eq (yas--fom-parent-field fom) field)
3330 (yas--mark-this-and-children-modified fom))
3331 (setq fom (yas--fom-next fom)))))
3333 (defun yas--make-move-active-field-overlay (snippet field)
3334 "Place the active field overlay in SNIPPET's FIELD.
3336 Move the overlay, or create it if it does not exit."
3337 (if (and yas--active-field-overlay
3338 (overlay-buffer yas--active-field-overlay))
3339 (move-overlay yas--active-field-overlay
3340 (yas--field-start field)
3341 (yas--field-end field))
3342 (setq yas--active-field-overlay
3343 (make-overlay (yas--field-start field)
3344 (yas--field-end field)
3346 (overlay-put yas--active-field-overlay 'priority 100)
3347 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3348 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3349 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3350 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3351 '(yas--on-field-overlay-modification))
3352 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3353 '(yas--on-field-overlay-modification))))
3355 (defvar yas--inhibit-overlay-hooks nil
3356 "Bind this temporarity to non-nil to prevent running `yas--on-*-modification'.")
3358 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3359 "Clears the field and updates mirrors, conditionally.
3361 Only clears the field if it hasn't been modified and it point it
3362 at field start. This hook doesn't do anything if an undo is in
3364 (unless (or yas--inhibit-overlay-hooks
3365 (yas--undo-in-progress))
3366 (let* ((field (overlay-get overlay 'yas--field))
3367 (number (and field (yas--field-number field)))
3368 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3370 (yas--advance-end-maybe field (overlay-end overlay))
3372 (yas--field-update-display field snippet))
3373 (yas--update-mirrors snippet))
3375 (when (and (not after?)
3376 (not (yas--field-modified-p field))
3377 (eq (point) (if (markerp (yas--field-start field))
3378 (marker-position (yas--field-start field))
3379 (yas--field-start field))))
3380 (yas--skip-and-clear field))
3381 (setf (yas--field-modified-p field) t))))))
3383 ;;; Apropos protection overlays:
3385 ;; These exist for nasty users who will try to delete parts of the
3386 ;; snippet outside the active field. Actual protection happens in
3387 ;; `yas--on-protection-overlay-modification'.
3389 ;; Currently this signals an error which inhibits the command. For
3390 ;; commands that move point (like `kill-line'), point is restored in
3391 ;; the `yas--post-command-handler' using a global
3392 ;; `yas--protection-violation' variable.
3394 ;; Alternatively, I've experimented with an implementation that
3395 ;; commits the snippet before actually calling `this-command'
3396 ;; interactively, and then signals an eror, which is ignored. but
3397 ;; blocks all other million modification hooks. This presented some
3398 ;; problems with stacked expansion.
3400 (defun yas--make-move-field-protection-overlays (snippet field)
3401 "Place protection overlays surrounding SNIPPET's FIELD.
3403 Move the overlays, or create them if they do not exit."
3404 (let ((start (yas--field-start field))
3405 (end (yas--field-end field)))
3406 ;; First check if the (1+ end) is contained in the buffer,
3407 ;; otherwise we'll have to do a bit of cheating and silently
3408 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3409 ;; when using stacked expansion
3411 (when (< (buffer-size) end)
3413 (yas--inhibit-overlay-hooks
3414 (goto-char (point-max))
3416 ;; go on to normal overlay creation/moving
3418 (cond ((and yas--field-protection-overlays
3419 (every #'overlay-buffer yas--field-protection-overlays))
3420 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3421 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3423 (setq yas--field-protection-overlays
3424 (list (make-overlay (1- start) start nil t nil)
3425 (make-overlay end (1+ end) nil t nil)))
3426 (dolist (ov yas--field-protection-overlays)
3427 (overlay-put ov 'face 'yas--field-debug-face)
3428 (overlay-put ov 'yas--snippet snippet)
3429 ;; (overlay-put ov 'evaporate t)
3430 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3432 (defvar yas--protection-violation nil
3433 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3435 Functions in the `post-command-hook', for example
3436 `yas--post-command-handler' can check it and reset its value to
3437 nil. The variables value is the point where the violation
3440 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3441 "Signals a snippet violation, then issues error.
3443 The error should be ignored in `debug-ignored-errors'"
3444 (unless yas--inhibit-overlay-hooks
3445 (cond ((not (or after?
3446 (yas--undo-in-progress)))
3447 (setq yas--protection-violation (point))
3448 (error "Exit the snippet first!")))))
3450 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3453 ;; Snippet expansion and "stacked" expansion:
3455 ;; Stacked expansion is when you try to expand a snippet when already
3456 ;; inside a snippet expansion.
3458 ;; The parent snippet does not run its fields modification hooks
3459 ;; (`yas--on-field-overlay-modification' and
3460 ;; `yas--on-protection-overlay-modification') while the child snippet
3461 ;; is active. This means, among other things, that the mirrors of the
3462 ;; parent snippet are not updated, this only happening when one exits
3463 ;; the child snippet.
3465 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3466 ;; bits of code in `yas-expand-snippet' and
3467 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3470 ;; This was thought to be safer in in an undo/redo perpective, but
3471 ;; maybe the correct implementation is to make the globals
3472 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3473 ;; snippet-local and be active even while the child snippet is
3474 ;; running. This would mean a lot of overlay modification hooks
3475 ;; running, but if managed correctly (including overlay priorities)
3476 ;; they should account for all situations...
3478 (defun yas-expand-snippet (content &optional start end expand-env)
3479 "Expand snippet CONTENT at current point.
3481 Text between START and END will be deleted before inserting
3482 template. EXPAND-ENV is are let-style variable to value bindings
3483 considered when expanding the snippet."
3484 (run-hooks 'yas-before-expand-snippet-hook)
3487 (let* ((yas-selected-text (or yas-selected-text
3488 (and (region-active-p)
3489 (buffer-substring-no-properties (region-beginning)
3492 (and (region-active-p)
3496 (and (region-active-p)
3499 (to-delete (and start
3501 (buffer-substring-no-properties start end)))
3504 (setq yas--indent-original-column (current-column))
3505 ;; Delete the region to delete, this *does* get undo-recorded.
3507 (when (and to-delete
3509 (delete-region start end))
3511 (cond ((listp content)
3512 ;; x) This is a snippet-command
3514 (yas--eval-lisp-no-saves content))
3516 ;; x) This is a snippet-snippet :-)
3518 ;; Narrow the region down to the content, shoosh the
3519 ;; `buffer-undo-list', and create the snippet, the new
3520 ;; snippet updates its mirrors once, so we are left with
3521 ;; some plain text. The undo action for deleting this
3522 ;; plain text will get recorded at the end.
3524 ;; stacked expansion: also shoosh the overlay modification hooks
3526 (narrow-to-region start start)
3527 (let ((buffer-undo-list t))
3528 ;; snippet creation might evaluate users elisp, which
3529 ;; might generate errors, so we have to be ready to catch
3530 ;; them mostly to make the undo information
3532 (setq yas--start-column (save-restriction (widen) (current-column)))
3533 (yas--inhibit-overlay-hooks
3536 (eval `(let* ,expand-env
3538 (yas--snippet-create (point-min) (point-max))))
3540 (yas--snippet-create (point-min) (point-max)))))))
3542 ;; stacked-expansion: This checks for stacked expansion, save the
3543 ;; `yas--previous-active-field' and advance its boudary.
3545 (let ((existing-field (and yas--active-field-overlay
3546 (overlay-buffer yas--active-field-overlay)
3547 (overlay-get yas--active-field-overlay 'yas--field))))
3548 (when existing-field
3549 (setf (yas--snippet-previous-active-field snippet) existing-field)
3550 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3552 ;; Exit the snippet immediately if no fields
3554 (unless (yas--snippet-fields snippet)
3555 (yas-exit-snippet snippet))
3557 ;; Push two undo actions: the deletion of the inserted contents of
3558 ;; the new snippet (without the "key") followed by an apply of
3559 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3561 ;; A small exception, if `yas-also-auto-indent-first-line'
3562 ;; is t and `yas--indent' decides to indent the line to a
3563 ;; point before the actual expansion point, undo would be
3564 ;; messed up. We call the early point "newstart"". case,
3565 ;; and attempt to fix undo.
3567 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3568 (end (overlay-end (yas--snippet-control-overlay snippet))))
3569 (when (< newstart start)
3570 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3571 (push (cons newstart end) buffer-undo-list)
3572 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3574 ;; Now, schedule a move to the first field
3576 (let ((first-field (car (yas--snippet-fields snippet))))
3578 (sit-for 0) ;; fix issue 125
3579 (yas--move-to-field snippet first-field)))
3580 (yas--message 3 "snippet expanded.")
3583 (defun yas--take-care-of-redo (beg end snippet)
3584 "Commits SNIPPET, which in turn pushes an undo action for
3587 Meant to exit in the `buffer-undo-list'."
3588 ;; slightly optimize: this action is only needed for snippets with
3589 ;; at least one field
3590 (when (yas--snippet-fields snippet)
3591 (yas--commit-snippet snippet)))
3593 (defun yas--snippet-revive (beg end snippet)
3594 "Revives the SNIPPET and creates a control overlay from BEG to
3597 BEG and END are, we hope, the original snippets boudaries. All
3598 the markers/points exiting existing inside SNIPPET should point
3599 to their correct locations *at the time the snippet is revived*.
3601 After revival, push the `yas--take-care-of-redo' in the
3603 ;; Reconvert all the points to markers
3605 (yas--points-to-markers snippet)
3606 ;; When at least one editable field existed in the zombie snippet,
3607 ;; try to revive the whole thing...
3609 (let ((target-field (or (yas--snippet-active-field snippet)
3610 (car (yas--snippet-fields snippet)))))
3612 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3613 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3615 (yas--move-to-field snippet target-field)
3617 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3618 buffer-undo-list))))
3620 (defun yas--snippet-create (begin end)
3621 "Creates a snippet from an template inserted between BEGIN and END.
3623 Returns the newly created snippet."
3624 (let ((snippet (yas--make-snippet)))
3626 (yas--snippet-parse-create snippet)
3628 ;; Sort and link each field
3629 (yas--snippet-sort-fields snippet)
3631 ;; Create keymap overlay for snippet
3632 (setf (yas--snippet-control-overlay snippet)
3633 (yas--make-control-overlay snippet (point-min) (point-max)))
3636 (goto-char (point-max))
3641 ;;; Apropos adjacencies and "fom's":
3643 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3644 ;; recently expanded snippet, we might actually have many fields,
3645 ;; mirrors (and the snippet exit) in the very same position in the
3646 ;; buffer. Therefore we need to single-link the
3647 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3648 ;; according to their original positions in the buffer.
3650 ;; Then we have operation `yas--advance-end-maybe' and
3651 ;; `yas--advance-start-maybe', which conditionally push the starts and
3652 ;; ends of these foms down the chain.
3654 ;; This allows for like the printf with the magic ",":
3656 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3657 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3659 (defun yas--fom-start (fom)
3660 (cond ((yas--field-p fom)
3661 (yas--field-start fom))
3662 ((yas--mirror-p fom)
3663 (yas--mirror-start fom))
3665 (yas--exit-marker fom))))
3667 (defun yas--fom-end (fom)
3668 (cond ((yas--field-p fom)
3669 (yas--field-end fom))
3670 ((yas--mirror-p fom)
3671 (yas--mirror-end fom))
3673 (yas--exit-marker fom))))
3675 (defun yas--fom-next (fom)
3676 (cond ((yas--field-p fom)
3677 (yas--field-next fom))
3678 ((yas--mirror-p fom)
3679 (yas--mirror-next fom))
3681 (yas--exit-next fom))))
3683 (defun yas--fom-parent-field (fom)
3684 (cond ((yas--field-p fom)
3685 (yas--field-parent-field fom))
3686 ((yas--mirror-p fom)
3687 (yas--mirror-parent-field fom))
3691 (defun yas--calculate-adjacencies (snippet)
3692 "Calculate adjacencies for fields or mirrors of SNIPPET.
3694 This is according to their relative positions in the buffer, and
3695 has to be called before the $-constructs are deleted."
3696 (cl-flet ((yas--fom-set-next-fom (fom nextfom)
3697 (cond ((yas--field-p fom)
3698 (setf (yas--field-next fom) nextfom))
3699 ((yas--mirror-p fom)
3700 (setf (yas--mirror-next fom) nextfom))
3702 (setf (yas--exit-next fom) nextfom))))
3703 (yas--compare-fom-begs (fom1 fom2)
3704 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3705 (yas--mirror-p fom2)
3706 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3707 (yas--link-foms (fom1 fom2)
3708 (yas--fom-set-next-fom fom1 fom2)))
3709 ;; make some yas--field, yas--mirror and yas--exit soup
3711 (when (yas--snippet-exit snippet)
3712 (push (yas--snippet-exit snippet) soup))
3713 (dolist (field (yas--snippet-fields snippet))
3715 (dolist (mirror (yas--field-mirrors field))
3716 (push mirror soup)))
3719 #'yas--compare-fom-begs))
3721 (reduce #'yas--link-foms soup)))))
3723 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3724 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3726 Use the tighest containing field if more than one field contains
3727 the mirror. Intended to be called *before* the dollar-regions are
3729 (let ((min (point-min))
3731 (dolist (field (yas--snippet-fields snippet))
3732 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3733 (<= (yas--mirror-end mirror) (yas--field-end field))
3734 (< min (yas--field-start field))
3735 (< (yas--field-end field) max))
3736 (setq min (yas--field-start field)
3737 max (yas--field-end field))
3738 (setf (yas--mirror-parent-field mirror) field)))))
3740 (defun yas--advance-end-maybe (fom newend)
3741 "Maybe advance FOM's end to NEWEND if it needs it.
3745 * call `yas--advance-start-maybe' on FOM's next fom.
3747 * in case FOM is field call `yas--advance-end-maybe' on its parent
3750 Also, if FOM is an exit-marker, always call
3751 `yas--advance-start-maybe' on its next fom. This is beacuse
3752 exit-marker have identical start and end markers.
3755 (cond ((and fom (< (yas--fom-end fom) newend))
3756 (set-marker (yas--fom-end fom) newend)
3757 (yas--advance-start-maybe (yas--fom-next fom) newend)
3758 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3760 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3762 (defun yas--advance-start-maybe (fom newstart)
3763 "Maybe advance FOM's start to NEWSTART if it needs it.
3765 If it does, also call `yas--advance-end-maybe' on FOM."
3766 (when (and fom (< (yas--fom-start fom) newstart))
3767 (set-marker (yas--fom-start fom) newstart)
3768 (yas--advance-end-maybe fom newstart)))
3770 (defun yas--advance-end-of-parents-maybe (field newend)
3771 "Like `yas--advance-end-maybe' but for parent fields.
3773 Only works for fields and doesn't care about the start of the
3774 next FOM. Works its way up recursively for parents of parents."
3776 (< (yas--field-end field) newend))
3777 (set-marker (yas--field-end field) newend)
3778 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3780 (defvar yas--dollar-regions nil
3781 "When expanding the snippet the \"parse-create\" functions add
3782 cons cells to this var")
3784 (defvar yas--backquote-markers-and-strings nil
3785 "List of (MARKER . STRING) marking where the the values
3786 from backquoted lisp expressions should be inserted at the end of
3789 (defun yas--snippet-parse-create (snippet)
3790 "Parse a recently inserted snippet template, creating all
3791 necessary fields, mirrors and exit points.
3793 Meant to be called in a narrowed buffer, does various passes"
3794 (let ((parse-start (point)))
3795 ;; Reset the yas--dollar-regions
3797 (setq yas--dollar-regions nil)
3798 ;; protect just the backquotes
3800 (yas--protect-escapes nil '(?`))
3801 ;; replace all backquoted expressions
3803 (goto-char parse-start)
3804 (yas--save-backquotes)
3805 ;; protect escaped characters
3807 (yas--protect-escapes)
3808 ;; parse fields with {}
3810 (goto-char parse-start)
3811 (yas--field-parse-create snippet)
3812 ;; parse simple mirrors and fields
3814 (goto-char parse-start)
3815 (yas--simple-mirror-parse-create snippet)
3816 ;; parse mirror transforms
3818 (goto-char parse-start)
3819 (yas--transform-mirror-parse-create snippet)
3820 ;; calculate adjacencies of fields and mirrors
3822 (yas--calculate-adjacencies snippet)
3823 ;; Delete $-constructs
3825 (yas--delete-regions yas--dollar-regions)
3826 ;; restore backquoted expression values
3828 (yas--restore-backquotes)
3831 (goto-char parse-start)
3832 (yas--restore-escapes)
3833 ;; update mirrors for the first time
3835 (yas--update-mirrors snippet)
3836 ;; indent the best we can
3838 (goto-char parse-start)
3839 (yas--indent snippet)))
3841 (defun yas--indent-according-to-mode (snippet-markers)
3842 "Indent current line according to mode, preserving
3844 ;;; Apropos indenting problems....
3846 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3847 ;; is available. Some implementations of these functions delete text
3848 ;; before they insert. If there happens to be a marker just after
3849 ;; the text being deleted, the insertion actually happens after the
3850 ;; marker, which misplaces it.
3852 ;; This would also happen if we had used overlays with the
3853 ;; `front-advance' property set to nil.
3855 ;; This is why I have these `trouble-markers', they are the ones at
3856 ;; they are the ones at the first non-whitespace char at the line
3857 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3858 ;; we should be at the correct to restore them to. All other
3859 ;; non-trouble-markers have been *pushed* and don't need special
3862 (goto-char (yas--real-line-beginning))
3863 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3869 (indent-according-to-mode)
3870 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3872 (mapc #'(lambda (marker)
3873 (set-marker marker (point)))
3876 (defvar yas--indent-original-column nil)
3877 (defun yas--indent (snippet)
3878 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3879 ;; Look for those $>
3881 (while (re-search-forward "$>" nil t)
3882 (delete-region (match-beginning 0) (match-end 0))
3883 (when (not (eq yas-indent-line 'auto))
3884 (yas--indent-according-to-mode snippet-markers))))
3885 ;; Now do stuff for 'fixed and 'auto
3887 (cond ((eq yas-indent-line 'fixed)
3888 (while (and (zerop (forward-line))
3889 (zerop (current-column)))
3890 (indent-to-column yas--indent-original-column)))
3891 ((eq yas-indent-line 'auto)
3892 (let ((end (set-marker (make-marker) (point-max)))
3893 (indent-first-line-p yas-also-auto-indent-first-line))
3894 (while (and (zerop (if indent-first-line-p
3897 (setq indent-first-line-p nil))
3901 (yas--indent-according-to-mode snippet-markers))))
3905 (defun yas--collect-snippet-markers (snippet)
3906 "Make a list of all the markers used by SNIPPET."
3908 (dolist (field (yas--snippet-fields snippet))
3909 (push (yas--field-start field) markers)
3910 (push (yas--field-end field) markers)
3911 (dolist (mirror (yas--field-mirrors field))
3912 (push (yas--mirror-start mirror) markers)
3913 (push (yas--mirror-end mirror) markers)))
3914 (let ((snippet-exit (yas--snippet-exit snippet)))
3915 (when (and snippet-exit
3916 (marker-buffer (yas--exit-marker snippet-exit)))
3917 (push (yas--exit-marker snippet-exit) markers)))
3920 (defun yas--real-line-beginning ()
3921 (let ((c (char-after (line-beginning-position)))
3922 (n (line-beginning-position)))
3923 (while (or (eql c ?\ )
3926 (setq c (char-after n)))
3929 (defun yas--escape-string (escaped)
3930 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3932 (defun yas--protect-escapes (&optional text escaped)
3933 "Protect all escaped characters with their numeric ASCII value.
3935 With optional string TEXT do it in string instead of buffer."
3936 (let ((changed-text text)
3937 (text-provided-p text))
3938 (mapc #'(lambda (escaped)
3940 (yas--replace-all (concat "\\" (char-to-string escaped))
3941 (yas--escape-string escaped)
3942 (when text-provided-p changed-text))))
3943 (or escaped yas--escaped-characters))
3946 (defun yas--restore-escapes (&optional text escaped)
3947 "Restore all escaped characters from their numeric ASCII value.
3949 With optional string TEXT do it in string instead of the buffer."
3950 (let ((changed-text text)
3951 (text-provided-p text))
3952 (mapc #'(lambda (escaped)
3954 (yas--replace-all (yas--escape-string escaped)
3955 (char-to-string escaped)
3956 (when text-provided-p changed-text))))
3957 (or escaped yas--escaped-characters))
3960 (defun yas--save-backquotes ()
3961 "Save all the \"`(lisp-expression)`\"-style expression
3962 with their evaluated value into `yas--backquote-markers-and-strings'"
3963 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3964 (let ((current-string (match-string-no-properties 1)) transformed)
3965 (delete-region (match-beginning 0) (match-end 0))
3966 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3967 (goto-char (match-beginning 0))
3969 (let ((marker (make-marker)))
3970 (insert "Y") ;; quite horrendous, I love it :)
3971 (set-marker marker (point))
3973 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3975 (defun yas--restore-backquotes ()
3976 "Replace all the markers in
3977 `yas--backquote-markers-and-strings' with their values"
3978 (while yas--backquote-markers-and-strings
3979 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3980 (marker (car marker-and-string))
3981 (string (cdr marker-and-string)))
3987 (set-marker marker nil)))))
3989 (defun yas--scan-sexps (from count)
3991 (with-syntax-table (standard-syntax-table)
3992 (scan-sexps from count))
3996 (defun yas--make-marker (pos)
3997 "Create a marker at POS with `nil' `marker-insertion-type'"
3998 (let ((marker (set-marker (make-marker) pos)))
3999 (set-marker-insertion-type marker nil)
4002 (defun yas--field-parse-create (snippet &optional parent-field)
4003 "Parse most field expressions, except for the simple one \"$n\".
4005 The following count as a field:
4007 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4009 * \"${n: text$(expression)}, the same with a lisp expression;
4010 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4012 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4014 When multiple expressions are found, only the last one counts."
4017 (while (re-search-forward yas--field-regexp nil t)
4018 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4019 (number (and (match-string-no-properties 1)
4020 (string-to-number (match-string-no-properties 1))))
4021 (brand-new-field (and real-match-end-0
4022 ;; break if on "$(" immediately
4023 ;; after the ":", this will be
4024 ;; caught as a mirror with
4026 (not (save-match-data
4027 (eq (string-match "$[ \t\n]*("
4028 (match-string-no-properties 2)) 0)))
4029 ;; allow ${0: some exit text}
4030 ;; (not (and number (zerop number)))
4031 (yas--make-field number
4032 (yas--make-marker (match-beginning 2))
4033 (yas--make-marker (1- real-match-end-0))
4035 (when brand-new-field
4036 (goto-char real-match-end-0)
4037 (push (cons (1- real-match-end-0) real-match-end-0)
4038 yas--dollar-regions)
4039 (push (cons (match-beginning 0) (match-beginning 2))
4040 yas--dollar-regions)
4041 (push brand-new-field (yas--snippet-fields snippet))
4044 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4045 (goto-char (point-min))
4046 (yas--field-parse-create snippet brand-new-field)))))))
4047 ;; if we entered from a parent field, now search for the
4048 ;; `yas--multi-dollar-lisp-expression-regexp'. THis is used for
4049 ;; primary field transformations
4053 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4054 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4055 ;; commit the primary field transformation if:
4057 ;; 1. we don't find it in yas--dollar-regions (a subnested
4058 ;; field) might have already caught it.
4060 ;; 2. we really make sure we have either two '$' or some
4061 ;; text and a '$' after the colon ':'. This is a FIXME: work
4062 ;; my regular expressions and end these ugly hacks.
4064 (when (and real-match-end-1
4065 (not (member (cons (match-beginning 0)
4067 yas--dollar-regions))
4069 (char-before (1- (match-beginning 1))))))
4070 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4072 (setf (yas--field-transform parent-field)
4073 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4074 (push (cons (match-beginning 0) real-match-end-1)
4075 yas--dollar-regions)))))))
4077 (defun yas--transform-mirror-parse-create (snippet)
4078 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
4079 (while (re-search-forward yas--transform-mirror-regexp nil t)
4080 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4081 (number (string-to-number (match-string-no-properties 1)))
4083 (not (zerop number))
4084 (yas--snippet-find-field snippet number)))
4086 (and real-match-end-0
4088 (yas--make-mirror (yas--make-marker (match-beginning 0))
4089 (yas--make-marker (match-beginning 0))
4091 (yas--restore-escapes
4092 (buffer-substring-no-properties (match-beginning 2)
4093 (1- real-match-end-0))))))))
4094 (when brand-new-mirror
4095 (push brand-new-mirror
4096 (yas--field-mirrors field))
4097 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4098 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4100 (defun yas--simple-mirror-parse-create (snippet)
4101 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
4102 (while (re-search-forward yas--simple-mirror-regexp nil t)
4103 (let ((number (string-to-number (match-string-no-properties 1))))
4104 (cond ((zerop number)
4106 (setf (yas--snippet-exit snippet)
4107 (yas--make-exit (yas--make-marker (match-end 0))))
4109 (goto-char (match-beginning 0))
4110 (when yas-wrap-around-region
4111 (cond (yas-selected-text
4112 (insert yas-selected-text))
4113 ((and (eq yas-wrap-around-region 'cua)
4116 (insert (prog1 (get-register ?0)
4117 (set-register ?0 nil))))))
4118 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4119 yas--dollar-regions)))
4121 (let ((field (yas--snippet-find-field snippet number)))
4123 (let ((brand-new-mirror (yas--make-mirror
4124 (yas--make-marker (match-beginning 0))
4125 (yas--make-marker (match-beginning 0))
4127 (push brand-new-mirror
4128 (yas--field-mirrors field))
4129 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4130 (push (yas--make-field number
4131 (yas--make-marker (match-beginning 0))
4132 (yas--make-marker (match-beginning 0))
4134 (yas--snippet-fields snippet))))
4135 (push (cons (match-beginning 0) (match-end 0))
4136 yas--dollar-regions))))))
4138 (defun yas--delete-regions (regions)
4139 "Sort disjuct REGIONS by start point, then delete from the back."
4140 (mapc #'(lambda (reg)
4141 (delete-region (car reg) (cdr reg)))
4144 (>= (car r1) (car r2))))))
4146 (defun yas--update-mirrors (snippet)
4147 "Updates all the mirrors of SNIPPET."
4149 (dolist (field-and-mirror (sort
4150 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4151 ;; where F is the field that M is mirroring
4153 (mapcan #'(lambda (field)
4154 (mapcar #'(lambda (mirror)
4155 (cons field mirror))
4156 (yas--field-mirrors field)))
4157 (yas--snippet-fields snippet))
4158 ;; then sort this list so that entries with mirrors with parent
4159 ;; fields appear before. This was important for fixing #290, and
4160 ;; luckily also handles the case where a mirror in a field causes
4161 ;; another mirror to need reupdating
4163 #'(lambda (field-and-mirror1 field-and-mirror2)
4164 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4165 (let* ((field (car field-and-mirror))
4166 (mirror (cdr field-and-mirror))
4167 (parent-field (yas--mirror-parent-field mirror)))
4168 ;; before updating a mirror with a parent-field, maybe advance
4172 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4173 ;; update this mirror
4175 (yas--mirror-update-display mirror field)
4176 ;; `yas--place-overlays' is needed if the active field and
4177 ;; protected overlays have been changed because of insertions
4178 ;; in `yas--mirror-update-display'
4180 (when (eq field (yas--snippet-active-field snippet))
4181 (yas--place-overlays snippet field))))))
4183 (defun yas--mirror-update-display (mirror field)
4184 "Update MIRROR according to FIELD (and mirror transform)."
4186 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4187 (reflection (and (not (and mirror-parent-field
4188 (yas--field-modified-p mirror-parent-field)))
4189 (or (yas--apply-transform mirror field 'empty-on-nil)
4190 (yas--field-text-for-display field)))))
4191 (when (and reflection
4192 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4193 (yas--mirror-end mirror)))))
4194 (goto-char (yas--mirror-start mirror))
4195 (yas--inhibit-overlay-hooks
4196 (insert reflection))
4197 (if (> (yas--mirror-end mirror) (point))
4198 (delete-region (point) (yas--mirror-end mirror))
4199 (set-marker (yas--mirror-end mirror) (point))
4200 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4201 ;; super-special advance
4202 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4204 (defun yas--field-update-display (field snippet)
4205 "Much like `yas--mirror-update-display', but for fields"
4206 (when (yas--field-transform field)
4207 (let ((transformed (and (not (eq (yas--field-number field) 0))
4208 (yas--apply-transform field field)))
4210 (when (and transformed
4211 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4212 (yas--field-end field)))))
4213 (setf (yas--field-modified-p field) t)
4214 (goto-char (yas--field-start field))
4215 (yas--inhibit-overlay-hooks
4216 (insert transformed)
4217 (if (> (yas--field-end field) (point))
4218 (delete-region (point) (yas--field-end field))
4219 (set-marker (yas--field-end field) (point))
4220 (yas--advance-start-maybe (yas--field-next field) (point)))
4224 ;;; Post-command hook:
4226 (defun yas--post-command-handler ()
4227 "Handles various yasnippet conditions after each command."
4228 (cond (yas--protection-violation
4229 (goto-char yas--protection-violation)
4230 (setq yas--protection-violation nil))
4231 ((eq 'undo this-command)
4233 ;; After undo revival the correct field is sometimes not
4234 ;; restored correctly, this condition handles that
4236 (let* ((snippet (car (yas--snippets-at-point)))
4237 (target-field (and snippet
4238 (find-if-not #'(lambda (field)
4239 (yas--field-probably-deleted-p snippet field))
4241 (cons (yas--snippet-active-field snippet)
4242 (yas--snippet-fields snippet)))))))
4244 (yas--move-to-field snippet target-field))))
4245 ((not (yas--undo-in-progress))
4246 ;; When not in an undo, check if we must commit the snippet
4247 ;; (user exited it).
4248 (yas--check-commit-snippet))))
4252 ;; The docstrings for some functions are generated dynamically
4253 ;; depending on the context.
4255 (put 'yas-expand 'function-documentation
4256 '(yas--expand-from-trigger-key-doc))
4257 (defun yas--expand-from-trigger-key-doc ()
4258 "A doc synthethizer for `yas--expand-from-trigger-key-doc'."
4259 (let ((fallback-description
4260 (cond ((eq yas-fallback-behavior 'call-other-command)
4261 (let* ((yas-minor-mode nil)
4262 (fallback (key-binding (read-kbd-macro (yas--trigger-key-for-fallback)))))
4264 (format " call command `%s'." (pp-to-string fallback)))
4266 ((eq yas-fallback-behavior 'return-nil)
4269 ", defer to `yas--fallback-behaviour' :-)"))))
4270 (concat "Expand a snippet before point. If no snippet
4271 expansion is possible,"
4272 fallback-description
4273 "\n\nOptional argument FIELD is for non-interactive use and is an
4274 object satisfying `yas--field-p' to restrict the expansion to.")))
4276 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4277 (defun yas--expand-from-keymap-doc ()
4278 "A doc synthethizer for `yas--expand-from-keymap-doc'."
4279 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4280 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4281 (when (eq this-command 'describe-key)
4282 (let* ((vec (this-single-command-keys))
4283 (templates (mapcan #'(lambda (table)
4284 (yas--fetch table vec))
4285 (yas--get-snippet-tables)))
4286 (yas--direct-keymaps nil)
4287 (fallback (key-binding vec)))
4288 (concat "In this case, "
4290 (concat "these snippets are bound to this key:\n"
4291 (yas--template-pretty-list templates)
4292 "\n\nIf none of these expands, "))
4294 (format "fallback `%s' will be called." (pp-to-string fallback)))
4295 "no fallback keybinding is called."))))))
4297 (defun yas--template-pretty-list (templates)
4299 (yas-buffer-local-condition 'always))
4300 (dolist (plate templates)
4301 (setq acc (concat acc "\n*) "
4302 (propertize (concat "\\\\snippet `" (car plate) "'")
4303 'yasnippet (cdr plate)))))
4306 (define-button-type 'help-snippet-def
4307 :supertype 'help-xref
4308 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4309 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4311 (defun yas--snippet-description-finish-runonce ()
4312 "Final adjustments for the help buffer when snippets are concerned."
4313 (yas--create-snippet-xrefs)
4314 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4316 (defun yas--create-snippet-xrefs ()
4318 (goto-char (point-min))
4319 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4320 (let ((template (get-text-property (match-beginning 1)
4323 (help-xref-button 1 'help-snippet-def template)
4324 (kill-region (match-end 1) (match-end 0))
4325 (kill-region (match-beginning 0) (match-beginning 1)))))))
4327 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4328 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4330 Remaining args as in `yas-expand-snippet'."
4331 (let* ((table (gethash mode-symbol yas--tables))
4332 (yas--current-template (and table
4333 (gethash uuid (yas--table-uuidhash table)))))
4334 (when yas--current-template
4335 (yas-expand-snippet (yas--template-content yas--current-template)))))
4339 (defvar yas-verbosity 4
4340 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4342 (defun yas--message (level message &rest args)
4343 (when (> yas-verbosity level)
4344 (message (apply #'yas--format message args))))
4346 (defun yas--format (format-control &rest format-args)
4347 (apply #'format (concat "[yas] " format-control) format-args))
4354 ;; `locate-dominating-file'
4355 ;; `region-active-p'
4357 ;; added for compatibility in emacsen < 23
4358 (unless (>= emacs-major-version 23)
4359 (unless (fboundp 'region-active-p)
4360 (defun region-active-p () (and transient-mark-mode mark-active)))
4362 (unless (fboundp 'locate-dominating-file)
4363 (defvar locate-dominating-stop-dir-regexp
4364 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4365 "Regexp of directory names which stop the search in `locate-dominating-file'.
4366 Any directory whose name matches this regexp will be treated like
4367 a kind of root directory by `locate-dominating-file' which will stop its search
4368 when it bumps into it.
4369 The default regexp prevents fruitless and time-consuming attempts to find
4370 special files in directories in which filenames are interpreted as hostnames,
4371 or mount points potentially requiring authentication as a different user.")
4373 (defun locate-dominating-file (file name)
4374 "Look up the directory hierarchy from FILE for a file named NAME.
4375 Stop at the first parent directory containing a file NAME,
4376 and return the directory. Return nil if not found."
4377 ;; We used to use the above locate-dominating-files code, but the
4378 ;; directory-files call is very costly, so we're much better off doing
4379 ;; multiple calls using the code in here.
4381 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4382 ;; `name' in /home or in /.
4383 (setq file (abbreviate-file-name file))
4386 ;; `user' is not initialized outside the loop because
4387 ;; `file' may not exist, so we may have to walk up part of the
4388 ;; hierarchy before we find the "initial UUID".
4391 (while (not (or root
4393 ;; FIXME: Disabled this heuristic because it is sometimes
4395 ;; As a heuristic, we stop looking up the hierarchy of
4396 ;; directories as soon as we find a directory belonging
4397 ;; to another user. This should save us from looking in
4398 ;; things like /net and /afs. This assumes that all the
4399 ;; files inside a project belong to the same user.
4400 ;; (let ((prev-user user))
4401 ;; (setq user (nth 2 (file-attributes file)))
4402 ;; (and prev-user (not (equal user prev-user))))
4403 (string-match locate-dominating-stop-dir-regexp file)))
4404 (setq try (file-exists-p (expand-file-name name file)))
4405 (cond (try (setq root file))
4406 ((equal file (setq prev-file file
4407 file (file-name-directory
4408 (directory-file-name file))))
4412 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4413 ;; (when it execute forward-char) and interrupt the after change
4414 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4415 ;; invoked. Here's a way to reproduce it:
4417 ;; # open a *new* Emacs.
4418 ;; # load yasnippet.
4419 ;; # open a *new* .cpp file.
4420 ;; # input "inc" and press TAB to expand the snippet.
4421 ;; # select the `#include <...>` snippet.
4422 ;; # type inside `<>`
4424 (defadvice c-neutralize-syntax-in-CPP
4425 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4426 "Adviced `c-neutralize-syntax-in-CPP' to properly
4427 handle the end-of-buffer error fired in it by calling
4428 `forward-char' at the end of buffer."
4431 (error (message (error-message-string err)))))
4433 ;; disable c-electric-* serial command in YAS fields
4434 (add-hook 'c-mode-common-hook
4436 (dolist (k '(":" ">" ";" "<" "{" "}"))
4437 (define-key (symbol-value (make-local-variable 'yas-keymap))
4438 k 'self-insert-command))))
4440 ;;; Backward compatibility to to yasnippet <= 0.7
4441 (defvar yas--exported-syms '(;; `defcustom's
4444 yas-prompt-functions
4446 yas-also-auto-indent-first-line
4451 yas-skip-and-clear-key
4452 yas-triggers-in-field
4453 yas-fallback-behavior
4454 yas-choose-keys-first
4455 yas-choose-tables-first
4458 yas-wrap-around-region
4461 yas-expand-only-for-last-commands
4462 yas-field-highlight-face
4464 ;; these vars can be customized as well
4470 yas-after-exit-snippet-hook
4471 yas-before-expand-snippet-hook
4472 yas-buffer-local-condition
4474 ;; prompting functions
4479 yas-completing-prompt
4482 ;; interactive functions
4487 yas-direct-keymaps-reload
4491 yas-compile-directory
4494 yas-expand-from-trigger-key
4495 yas-expand-from-keymap
4497 yas-visit-snippet-file
4499 yas-load-snippet-buffer
4502 yas-next-field-or-maybe-expand
4507 yas-exit-all-snippets
4508 yas-skip-and-clear-or-delete-char
4510 ;; symbols that I "exported" for use
4511 ;; in snippets and hookage
4529 yas-default-from-field
4532 yas-define-condition-cache
4533 yas-hippie-try-expand
4536 ;; debug definitions
4537 ;; yas-debug-snippet-vars
4538 ;; yas-exterminate-package
4541 ;; testing definitions
4542 ;; yas-should-expand
4543 ;; yas-should-not-expand
4545 ;; yas-make-file-or-dirs
4547 ;; yas-saving-variables
4548 ;; yas-call-with-snippet-dirs
4549 ;; yas-with-snippet-dirs
4551 "Exported yassnippet symbols.
4553 i.e. ones that I will try to keep in future yasnippet versions
4554 and ones that other elisp libraries can more or less safely rely
4557 (defvar yas--dont-backport '(yas-active-keys)
4558 "Exported symbols that don't map back to \"yas/*\" variants")
4560 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4561 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4563 (make-obsolete-variable backported sym "yasnippet 0.8")
4564 (defvaralias backported sym))
4566 (make-obsolete backported sym "yasnippet 0.8")
4567 (defalias backported sym))))
4570 (provide 'yasnippet)
4572 ;;; yasnippet.el ends here