1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is normally bound to TAB, but you can customize it in
67 ;; `yas-minor-mode-map'.
69 ;; M-x yas-load-directory
71 ;; Prompts you for a directory hierarchy of snippets to load.
73 ;; M-x yas-insert-snippet
75 ;; Prompts you for possible snippet expansion if that is
76 ;; possible according to buffer-local and snippet-local
77 ;; expansion conditions. With prefix argument, ignore these
80 ;; M-x yas-visit-snippet-file
82 ;; Prompts you for possible snippet expansions like
83 ;; `yas-insert-snippet', but instead of expanding it, takes
84 ;; you directly to the snippet definition's file, if it
87 ;; M-x yas-new-snippet
89 ;; Lets you create a new snippet file in the correct
90 ;; subdirectory of `yas-snippet-dirs', according to the
93 ;; M-x yas-load-snippet-buffer
95 ;; When editing a snippet, this loads the snippet. This is
96 ;; bound to "C-c C-c" while in the `snippet-mode' editing
99 ;; M-x yas-tryout-snippet
101 ;; When editing a snippet, this opens a new empty buffer,
102 ;; sets it to the appropriate major mode and inserts the
103 ;; snippet there, so you can see what it looks like. This is
104 ;; bound to "C-c C-t" while in `snippet-mode'.
106 ;; M-x yas-describe-tables
108 ;; Lists known snippets in a separate buffer. User is
109 ;; prompted as to whether only the currently active tables
110 ;; are to be displayed, or all the tables for all major
113 ;; If you have `dropdown-list' installed, you can optionally use it
114 ;; as the preferred "prompting method", putting in your .emacs file,
117 ;; (require 'dropdown-list)
118 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
120 ;; yas-completing-prompt))
122 ;; Also check out the customization group
124 ;; M-x customize-group RET yasnippet RET
126 ;; If you use the customization group to set variables
127 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
128 ;; "yasnippet.el" is present in the `load-path' *before* the
129 ;; `custom-set-variables' is executed in your .emacs file.
131 ;; For more information and detailed usage, refer to the project page:
132 ;; http://github.com/capitaomorte/yasnippet
141 (defvar yas--editing-template)
142 (defvar yas--guessed-modes)
143 (defvar yas--indent-original-column)
144 (defvar yas--scheduled-jit-loads)
146 (defvar yas-selected-text)
147 (defvar yas-verbosity))
151 ;;; User customizable variables
153 (defgroup yasnippet nil
154 "Yet Another Snippet extension"
157 (defvar yas--load-file-name load-file-name
158 "Store the filename that yasnippet.el was originally loaded from.")
160 (defcustom yas-snippet-dirs (remove nil
161 (list "~/.emacs.d/snippets"
162 (when yas--load-file-name
163 (concat (file-name-directory yas--load-file-name) "snippets"))))
164 "Directory or list of snippet dirs for each major mode.
166 The directory where user-created snippets are to be stored. Can
167 also be a list of directories. In that case, when used for
168 bulk (re)loading of snippets (at startup or via
169 `yas-reload-all'), directories appearing earlier in the list
170 shadow other dir's snippets. Also, the first directory is taken
171 as the default for storing the user's new snippets."
172 :type '(choice (string :tag "Single directory (string)")
173 (repeat :args (string) :tag "List of directories (strings)"))
176 :set #'(lambda (symbol new)
177 (let ((old (and (boundp symbol)
178 (symbol-value symbol))))
179 (set-default symbol new)
180 (unless (or (not (fboundp 'yas-reload-all))
184 (defun yas-snippet-dirs ()
185 "Returns `yas-snippet-dirs' (which see) as a list."
186 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
188 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
190 (defcustom yas-new-snippet-default "\
191 # -*- mode: snippet -*-
193 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
194 # binding: ${4:direct-keybinding}}${5:
195 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
199 "Default snippet to use when creating a new snippet."
203 (defcustom yas-prompt-functions '(yas-x-prompt
205 yas-completing-prompt
208 "Functions to prompt for keys, templates, etc interactively.
210 These functions are called with the following arguments:
212 - PROMPT: A string to prompt the user
214 - CHOICES: a list of strings or objects.
216 - optional DISPLAY-FN : A function that, when applied to each of
217 the objects in CHOICES will return a string.
219 The return value of any function you put here should be one of
220 the objects in CHOICES, properly formatted with DISPLAY-FN (if
223 - To signal that your particular style of prompting is
224 unavailable at the moment, you can also have the function return
227 - To signal that the user quit the prompting process, you can
230 (signal 'quit \"user quit!\")."
231 :type '(repeat function)
234 (defcustom yas-indent-line 'auto
235 "Controls indenting applied to a recent snippet expansion.
237 The following values are possible:
239 - `fixed' Indent the snippet to the current column;
241 - `auto' Indent each line of the snippet with `indent-according-to-mode'
243 Every other value means don't apply any snippet-side indentation
244 after expansion (the manual per-line \"$>\" indentation still
246 :type '(choice (const :tag "Nothing" nothing)
247 (const :tag "Fixed" fixed)
248 (const :tag "Auto" auto))
251 (defcustom yas-also-auto-indent-first-line nil
252 "Non-nil means also auto indent first line according to mode.
254 Naturally this is only valid when `yas-indent-line' is `auto'"
258 (defcustom yas-snippet-revival t
259 "Non-nil means re-activate snippet fields after undo/redo."
263 (defcustom yas-triggers-in-field nil
264 "If non-nil, allow stacked expansions (snippets inside snippets).
266 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
271 (defcustom yas-fallback-behavior 'call-other-command
272 "How to act when `yas-expand' does *not* expand a snippet.
274 - `call-other-command' means try to temporarily disable YASnippet
275 and call the next command bound to whatever key was used to
278 - nil or the symbol `return-nil' mean do nothing. (and
279 `yas-expand' returns nil)
281 - A Lisp form (apply COMMAND . ARGS) means interactively call
282 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
283 with ARGS as arguments."
284 :type '(choice (const :tag "Call previous command" call-other-command)
285 (const :tag "Do nothing" return-nil))
288 (defcustom yas-choose-keys-first nil
289 "If non-nil, prompt for snippet key first, then for template.
291 Otherwise prompts for all possible snippet names.
293 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
297 (defcustom yas-choose-tables-first nil
298 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
300 Otherwise, user chooses between the merging together of all
303 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
307 (defcustom yas-use-menu 'abbreviate
308 "Display a YASnippet menu in the menu bar.
310 When non-nil, submenus for each snippet table will be listed
311 under the menu \"Yasnippet\".
313 - If set to `abbreviate', only the current major-mode
314 menu and the modes set in `yas-extra-modes' are listed.
316 - If set to `full', every submenu is listed
318 - It set to nil, don't display a menu at all (this requires a
319 `yas-reload-all' call if the menu is already visible).
321 Any other non-nil value, every submenu is listed."
322 :type '(choice (const :tag "Full" full)
323 (const :tag "Abbreviate" abbreviate)
324 (const :tag "No menu" nil))
327 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
329 (char-to-string ?\x21E5))) ;; little ->| sign
331 "The text that will be used in menu to represent the trigger."
335 (defcustom yas-wrap-around-region nil
336 "If non-nil, snippet expansion wraps around selected region.
338 The wrapping occurs just before the snippet's exit marker. This
339 can be overridden on a per-snippet basis."
343 (defcustom yas-good-grace t
344 "If non-nil, don't raise errors in inline elisp evaluation.
346 An error string \"[yas] error\" is returned instead."
350 (defcustom yas-visit-from-menu nil
351 "If non-nil visit snippets's files from menu, instead of expanding them.
353 This can only work when snippets are loaded from files."
357 (defcustom yas-expand-only-for-last-commands nil
358 "List of `last-command' values to restrict tab-triggering to, or nil.
360 Leave this set at nil (the default) to be able to trigger an
361 expansion simply by placing the cursor after a valid tab trigger,
362 using whichever commands.
364 Optionally, set this to something like '(self-insert-command) if
365 you to wish restrict expansion to only happen when the last
366 letter of the snippet tab trigger was typed immediately before
367 the trigger key itself."
368 :type '(repeat function)
371 ;; Only two faces, and one of them shouldn't even be used...
373 (defface yas-field-highlight-face
374 '((t (:inherit 'region)))
375 "The face used to highlight the currently active field of a snippet"
378 (defface yas--field-debug-face
380 "The face used for debugging some overlays normally hidden"
384 ;;; User-visible variables
386 (defvar yas-keymap (let ((map (make-sparse-keymap)))
387 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
388 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
389 (define-key map [(shift tab)] 'yas-prev-field)
390 (define-key map [backtab] 'yas-prev-field)
391 (define-key map (kbd "C-g") 'yas-abort-snippet)
392 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
394 "The active keymap while a snippet expansion is in progress.")
396 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
397 "List of character syntaxes used to find a trigger key before point.
398 The list is tried in the order while scanning characters
399 backwards from point. For example, if the list is '(\"w\" \"w_\")
400 first look for trigger keys which are composed exclusively of
401 \"word\"-syntax characters, and then, if that fails, look for
402 keys which are either of \"word\" or \"symbol\"
403 syntax. Triggering after
407 will, according to the \"w\" element first try \"bar\". If that
408 isn't a trigger key, \"foo-bar\" is tried, respecting a second
411 (defvar yas-after-exit-snippet-hook
413 "Hooks to run after a snippet exited.
415 The hooks will be run in an environment where some variables bound to
418 `yas-snippet-beg' : The beginning of the region of the snippet.
420 `yas-snippet-end' : Similar to beg.
422 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
424 (defvar yas-before-expand-snippet-hook
426 "Hooks to run just before expanding a snippet.")
428 (defvar yas-buffer-local-condition
429 '(if (and (or (fourth (syntax-ppss))
430 (fifth (syntax-ppss)))
432 (eq this-command 'yas-expand-from-trigger-key))
433 '(require-snippet-condition . force-in-comment)
435 "Snippet expanding condition.
437 This variable is a Lisp form which is evaluated every time a
438 snippet expansion is attempted:
440 * If it evaluates to nil, no snippets can be expanded.
442 * If it evaluates to the a cons (require-snippet-condition
445 * Snippets bearing no \"# condition:\" directive are not
448 * Snippets bearing conditions that evaluate to nil (or
449 produce an error) won't be considered.
451 * If the snippet has a condition that evaluates to non-nil
454 * If REQUIREMENT is t, the snippet is considered
456 * If REQUIREMENT is `eq' RESULT, the snippet is
459 * Otherwise, the snippet is not considered.
461 * If it evaluates to the symbol 'always, all snippets are
462 considered for expansion, regardless of any conditions.
464 * If it evaluates to t or some other non-nil value
466 * Snippet bearing no conditions, or conditions that
467 evaluate to non-nil, are considered for expansion.
469 * Otherwise, the snippet is not considered.
471 Here's an example preventing snippets from being expanded from
472 inside comments, in `python-mode' only, with the exception of
473 snippets returning the symbol 'force-in-comment in their
476 (add-hook 'python-mode-hook
478 (setq yas-buffer-local-condition
479 '(if (python-in-string/comment)
480 '(require-snippet-condition . force-in-comment)
483 The default value is similar, it filters out potential snippet
484 expansions inside comments and string literals, unless the
485 snippet itself contains a condition that returns the symbol
486 `force-in-comment'.")
489 ;;; Internal variables
491 (defvar yas--version "0.8.0beta")
493 (defvar yas--menu-table (make-hash-table)
494 "A hash table of MAJOR-MODE symbols to menu keymaps.")
496 (defvar yas--known-modes
497 '(ruby-mode rst-mode markdown-mode)
498 "A list of mode which is well known but not part of Emacs.")
500 (defvar yas--escaped-characters
501 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
502 "List of characters which *might* need to be escaped.")
504 (defconst yas--field-regexp
505 "${\\([0-9]+:\\)?\\([^}]*\\)}"
506 "A regexp to *almost* recognize a field.")
508 (defconst yas--multi-dollar-lisp-expression-regexp
509 "$+[ \t\n]*\\(([^)]*)\\)"
510 "A regexp to *almost* recognize a \"$(...)\" expression.")
512 (defconst yas--backquote-lisp-expression-regexp
514 "A regexp to recognize a \"`lisp-expression`\" expression." )
516 (defconst yas--transform-mirror-regexp
517 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
518 "A regexp to *almost* recognize a mirror with a transform.")
520 (defconst yas--simple-mirror-regexp
522 "A regexp to recognize a simple mirror.")
524 (defvar yas--snippet-id-seed 0
525 "Contains the next id for a snippet.")
527 (defun yas--snippet-next-id ()
528 (let ((id yas--snippet-id-seed))
529 (incf yas--snippet-id-seed)
535 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
536 (defvar last-buffer-undo-list nil)
538 (defvar yas--minor-mode-menu nil
539 "Holds the YASnippet menu.")
541 (defun yas--init-minor-keymap ()
542 "Set up the `yas-minor-mode' keymap."
543 (let ((map (make-sparse-keymap)))
545 (easy-menu-define yas--minor-mode-menu
547 "Menu used when `yas-minor-mode' is active."
550 ["Expand trigger" yas-expand
551 :help "Possibly expand tab trigger before point"]
552 ["Insert at point..." yas-insert-snippet
553 :help "Prompt for an expandable snippet and expand it at point"]
554 ["New snippet..." yas-new-snippet
555 :help "Create a new snippet in an appropriate directory"]
556 ["Visit snippet file..." yas-visit-snippet-file
557 :help "Prompt for an expandable snippet and find its file"]
559 ("Snippet menu behaviour"
560 ["Visit snippets" (setq yas-visit-from-menu t)
561 :help "Visit snippets from the menu"
562 :active t :style radio :selected yas-visit-from-menu]
563 ["Expand snippets" (setq yas-visit-from-menu nil)
564 :help "Expand snippets from the menu"
565 :active t :style radio :selected (not yas-visit-from-menu)]
567 ["Show all known modes" (setq yas-use-menu 'full)
568 :help "Show one snippet submenu for each loaded table"
569 :active t :style radio :selected (eq yas-use-menu 'full)]
570 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
571 :help "Show only snippet submenus for the current active modes"
572 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
574 ["Auto" (setq yas-indent-line 'auto)
575 :help "Indent each line of the snippet with `indent-according-to-mode'"
576 :active t :style radio :selected (eq yas-indent-line 'auto)]
577 ["Fixed" (setq yas-indent-line 'fixed)
578 :help "Indent the snippet to the current column"
579 :active t :style radio :selected (eq yas-indent-line 'fixed)]
580 ["None" (setq yas-indent-line 'none)
581 :help "Don't apply any particular snippet indentation after expansion"
582 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
584 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
585 (not yas-also-auto-indent-first-line))
586 :help "When auto-indenting also, auto indent the first line menu"
587 :active (eq yas-indent-line 'auto)
588 :style toggle :selected yas-also-auto-indent-first-line]
591 ["System X-widget" (setq yas-prompt-functions
593 (remove 'yas-x-prompt
594 yas-prompt-functions)))
595 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
596 :active t :style radio :selected (eq (car yas-prompt-functions)
598 ["Dropdown-list" (setq yas-prompt-functions
599 (cons 'yas-dropdown-prompt
600 (remove 'yas-dropdown-prompt
601 yas-prompt-functions)))
602 :help "Use a special dropdown list"
603 :active t :style radio :selected (eq (car yas-prompt-functions)
604 'yas-dropdown-prompt)]
605 ["Ido" (setq yas-prompt-functions
606 (cons 'yas-ido-prompt
607 (remove 'yas-ido-prompt
608 yas-prompt-functions)))
609 :help "Use an ido-style minibuffer prompt"
610 :active t :style radio :selected (eq (car yas-prompt-functions)
612 ["Completing read" (setq yas-prompt-functions
613 (cons 'yas-completing-prompt
614 (remove 'yas-completing-prompt
615 yas-prompt-functions)))
616 :help "Use a normal minibuffer prompt"
617 :active t :style radio :selected (eq (car yas-prompt-functions)
618 'yas-completing-prompt)]
621 ["Wrap region in exit marker"
622 (setq yas-wrap-around-region
623 (not yas-wrap-around-region))
624 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
625 :style toggle :selected yas-wrap-around-region]
626 ["Allow stacked expansions "
627 (setq yas-triggers-in-field
628 (not yas-triggers-in-field))
629 :help "If non-nil allow snippets to be triggered inside other snippet fields"
630 :style toggle :selected yas-triggers-in-field]
631 ["Revive snippets on undo "
632 (setq yas-snippet-revival
633 (not yas-snippet-revival))
634 :help "If non-nil allow snippets to become active again after undo"
635 :style toggle :selected yas-snippet-revival]
638 (not yas-good-grace))
639 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
640 :style toggle :selected yas-good-grace]
643 ["Load snippets..." yas-load-directory
644 :help "Load snippets from a specific directory"]
645 ["Reload everything" yas-reload-all
646 :help "Cleanup stuff, reload snippets, rebuild menus"]
648 :help "Display some information about YASnippet"])))
650 ;; Now for the stuff that has direct keybindings
652 (define-key map [(tab)] 'yas-expand)
653 (define-key map (kbd "TAB") 'yas-expand)
654 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
655 (define-key map "\C-c&\C-n" 'yas-new-snippet)
656 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
659 (defvar yas-minor-mode-map (yas--init-minor-keymap)
660 "The keymap used when `yas-minor-mode' is active.")
662 (defvar yas--tables (make-hash-table)
663 "A hash table of mode symbols to `yas--table' objects.")
665 (defvar yas--parents (make-hash-table)
666 "A hash table of mode symbols do lists of direct parent mode symbols.
668 This list is populated when reading the \".yas-parents\" files
669 found when traversing snippet directories with
670 `yas-load-directory'.
672 There might be additional parenting information stored in the
673 `derived-mode-parent' property of some mode symbols, but that is
676 (defvar yas--ancestors (make-hash-table)
677 "A hash table of mode symbols do lists of all parent mode symbols.
679 A cache managed by `yas--all-parents'")
681 (defvar yas--direct-keymaps (list)
682 "Keymap alist supporting direct snippet keybindings.
684 This variable is placed in `emulation-mode-map-alists'.
686 Its elements looks like (TABLE-NAME . KEYMAP). They're
687 instantiated on `yas-reload-all' but KEYMAP is added to only when
688 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
689 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
690 defined direct keybindings to the command
691 `yas-expand-from-keymap' which then which snippet to expand.")
693 (defun yas-direct-keymaps-reload ()
694 "Force reload the direct keybinding for active snippet tables."
696 (setq yas--direct-keymaps nil)
697 (maphash #'(lambda (name table)
698 (push (cons (intern (format "yas--direct-%s" name))
699 (yas--table-direct-keymap table))
700 yas--direct-keymaps))
703 (defun yas--modes-to-activate ()
704 "Compute list of mode symbols that are active for `yas-expand'
706 (let ((modes-to-activate (list major-mode))
708 (while (setq mode (get mode 'derived-mode-parent))
709 (push mode modes-to-activate))
710 (dolist (mode (yas-extra-modes))
711 (push mode modes-to-activate))
713 (append modes-to-activate
714 (mapcan #'(lambda (mode)
715 (yas--all-parents mode))
716 modes-to-activate)))))
718 (defvar yas-minor-mode-hook nil
719 "Hook run when `yas-minor-mode' is turned on.")
722 (define-minor-mode yas-minor-mode
723 "Toggle YASnippet mode.
725 When YASnippet mode is enabled, `yas-expand', normally bound to
726 the TAB key, expands snippets of code depending on the major
729 With no argument, this command toggles the mode.
730 positive prefix argument turns on the mode.
731 Negative prefix argument turns off the mode.
734 \\{yas-minor-mode-map}"
736 ;; The indicator for the mode line.
739 (cond (yas-minor-mode
740 ;; Install the direct keymaps in `emulation-mode-map-alists'
741 ;; (we use `add-hook' even though it's not technically a hook,
742 ;; but it works). Then define variables named after modes to
743 ;; index `yas--direct-keymaps'.
745 ;; Also install the post-command-hook.
747 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
748 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
749 ;; Set the `yas--direct-%s' vars for direct keymap expansion
751 (dolist (mode (yas--modes-to-activate))
752 (let ((name (intern (format "yas--direct-%s" mode))))
753 (set-default name nil)
754 (set (make-local-variable name) t)))
757 (yas--load-pending-jits))
759 ;; Uninstall the direct keymaps and the post-command hook
761 (remove-hook 'post-command-hook 'yas--post-command-handler t)
762 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
764 (defvar yas-dont-activate '(minibufferp)
765 "If non-nil don't let `yas-global-mode' affect some buffers.
767 If a function of zero arguments, then its result is used.
769 If a list of functions, then all functions must return nil to
770 activate yas for this buffer.
772 In Emacsen <= 23, this variable is buffer-local. Because
773 `yas-minor-mode-on' is called by `yas-global-mode' after
774 executing the buffer's major mode hook, setting this variable
775 there is an effective way to define exceptions to the \"global\"
776 activation behaviour.
778 In Emacsen > 23, only the global value is used. To define
779 per-mode exceptions to the \"global\" activation behaviour, call
780 `yas-minor-mode' with a negative argument directily in the major
782 (unless (> emacs-major-version 23)
783 (make-variable-buffer-local 'yas-dont-activate))
786 (defun yas-minor-mode-on ()
787 "Turn on YASnippet minor mode.
789 Honour `yas-dont-activate', which see."
791 ;; Check `yas-dont-activate'
792 (unless (cond ((functionp yas-dont-activate)
793 (funcall yas-dont-activate))
794 ((consp yas-dont-activate)
795 (some #'funcall yas-dont-activate))
800 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
804 (defun yas--global-mode-reload-with-jit-maybe ()
805 "Run `yas-reload-all' when `yas-global-mode' is on."
806 (when yas-global-mode (yas-reload-all)))
808 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
813 (defvar yas--font-lock-keywords
814 (append '(("^#.*$" . font-lock-comment-face))
815 lisp-font-lock-keywords
816 lisp-font-lock-keywords-1
817 lisp-font-lock-keywords-2
819 (0 font-lock-keyword-face)
820 (1 font-lock-string-face t))
822 (0 font-lock-keyword-face)
823 (1 font-lock-warning-face t))
824 ("${" font-lock-keyword-face)
825 ("$[0-9]+?" font-lock-preprocessor-face)
826 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
828 (0 font-lock-keyword-face)))))
830 (defun yas--init-major-keymap ()
831 "Setup YASnippet major-mode keymap."
832 (let ((map (make-sparse-keymap)))
833 (easy-menu-define nil
835 "Menu used when snippet-mode is active."
837 (mapcar #'(lambda (ent)
839 (define-key map (third ent) (second ent)))
840 (vector (first ent) (second ent) t))
842 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
843 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
846 (defvar snippet-mode-map
847 (yas--init-major-keymap)
848 "The keymap used when `snippet-mode' is active.")
851 (define-derived-mode snippet-mode text-mode "Snippet"
852 "A mode for editing yasnippets"
853 (setq font-lock-defaults '(yas--font-lock-keywords))
854 (set (make-local-variable 'require-final-newline) nil)
855 (set (make-local-variable 'comment-start) "#")
856 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
860 ;;; Internal structs for template management
862 (defstruct (yas--template (:constructor yas--make-blank-template))
863 "A template for a snippet."
873 group ;; as dictated by the #group: directive or .yas-make-groups
874 perm-group ;; as dictated by `yas-define-menu'
878 (defun yas--populate-template (template &rest args)
879 "Helper function to populate TEMPLATE with properties."
883 (position (intern (substring (symbol-name (car args)) 1))
884 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
886 (setq args (cddr args)))
889 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
890 "A table to store snippets for a particular mode.
892 Has the following fields:
896 A symbol name normally corresponding to a major mode, but can
897 also be a pseudo major-mode to be referenced in
898 `yas-extra-modes', for example.
902 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
903 a string or a vector, where the former is the snippet's trigger
904 and the latter means it's a direct keybinding. NAMEHASH is yet
905 another hash of (NAME . TEMPLATE) where NAME is the snippet's
906 name and TEMPLATE is a `yas--template' object.
908 `yas--table-direct-keymap'
910 A keymap for the snippets in this table that have direct
911 keybindings. This is kept in sync with the keyhash, i.e., all
912 the elements of the keyhash that are vectors appear here as
913 bindings to `yas-expand-from-keymap'.
915 `yas--table-uuidhash'
917 A hash table mapping snippets uuid's to the same `yas--template'
918 objects. A snippet uuid defaults to the snippet's name.
921 (hash (make-hash-table :test 'equal))
922 (uuidhash (make-hash-table :test 'equal))
924 (direct-keymap (make-sparse-keymap)))
926 (defun yas--get-template-by-uuid (mode uuid)
927 "Find the snippet template in MODE by its UUID."
928 (let* ((table (gethash mode yas--tables mode)))
930 (gethash uuid (yas--table-uuidhash table)))))
932 ;; Apropos storing/updating in TABLE, this works in two steps:
934 ;; 1. `yas--remove-template-by-uuid' removes any
935 ;; keyhash-namehash-template mappings from TABLE, grabbing the
936 ;; snippet by its uuid. Also removes mappings from TABLE's
937 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
938 ;; of potentially stale menu bindings right?.)
940 ;; 2. `yas--add-template' adds this all over again.
942 ;; Create a new or add to an existing keyhash-namehash mapping.
944 ;; For reference on understanding this, consider three snippet
947 ;; A: # name: The Foo
949 ;; # binding: C-c M-l
951 ;; B: # name: Mrs Foo
954 ;; C: # name: The Bar
955 ;; # binding: C-c M-l
960 ;; keyhash namehashes(3) yas--template structs(4)
961 ;; -----------------------------------------------------
964 ;; "foo" ---> "The Foo" ---> [yas--template A] |
965 ;; "Mrs Foo" ---> [yas--template B] |
967 ;; [C-c M-l] ---> "The Foo" -------------------------/
968 ;; "The Bar" ---> [yas--template C]
970 ;; "baz" ---> "Baz" ---> [yas--template D]
972 ;; Additionally, since uuid defaults to the name, we have a
973 ;; `yas--table-uuidhash' for TABLE
975 ;; uuidhash yas--template structs
976 ;; -------------------------------
977 ;; "The Foo" ---> [yas--template A]
978 ;; "Mrs Foo" ---> [yas--template B]
979 ;; "The Bar" ---> [yas--template C]
980 ;; "Baz" ---> [yas--template D]
982 ;; FIXME: the more I look at this data-structure the more I think I'm
983 ;; stupid. There has to be an easier way (but beware lots of code
986 (defun yas--remove-template-by-uuid (table uuid)
987 "Remove from TABLE a template identified by UUID."
988 (let ((template (gethash uuid (yas--table-uuidhash table))))
990 (let* ((name (yas--template-name template))
992 ;; Remove the name from each of the targeted namehashes
994 (maphash #'(lambda (k v)
995 (let ((template (gethash name v)))
997 (eq uuid (yas--template-uuid template)))
999 (when (zerop (hash-table-count v))
1000 (push k empty-keys)))))
1001 (yas--table-hash table))
1002 ;; Remove the namehash themselves if they've become empty
1004 (dolist (key empty-keys)
1006 (define-key (yas--table-direct-keymap table) key nil))
1007 (remhash key (yas--table-hash table)))
1009 ;; Finally, remove the uuid from the uuidhash
1011 (remhash uuid (yas--table-uuidhash table))))))
1013 (defun yas--add-template (table template)
1014 "Store in TABLE the snippet template TEMPLATE.
1016 KEY can be a string (trigger key) of a vector (direct
1018 (let ((name (yas--template-name template))
1019 (key (yas--template-key template))
1020 (keybinding (yas--template-keybinding template))
1021 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1022 (dolist (k (remove nil (list key keybinding)))
1026 (yas--table-hash table))
1028 (make-hash-table :test 'equal)
1029 (yas--table-hash table))))
1031 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1033 ;; Update TABLE's `yas--table-uuidhash'
1034 (puthash (yas--template-uuid template)
1036 (yas--table-uuidhash table))))
1038 (defun yas--update-template (table template)
1039 "Add or update TEMPLATE in TABLE.
1041 Also takes care of adding and updating to the associated menu."
1042 ;; Remove from table by uuid
1044 (yas--remove-template-by-uuid table (yas--template-uuid template))
1045 ;; Add to table again
1047 (yas--add-template table template)
1048 ;; Take care of the menu
1051 (yas--update-template-menu table template)))
1053 (defun yas--update-template-menu (table template)
1054 "Update every menu-related for TEMPLATE."
1055 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1056 (key (yas--template-key template))
1057 (keybinding (yas--template-keybinding template)))
1058 ;; The snippet might have changed name or keys, so update
1059 ;; user-visible strings
1061 (unless (eq (cdr menu-binding-pair) :none)
1062 ;; the menu item name
1064 (setf (cadar menu-binding-pair) (yas--template-name template))
1065 ;; the :keys information (also visible to the user)
1066 (setf (getf (cdr (car menu-binding-pair)) :keys)
1067 (or (and keybinding (key-description keybinding))
1068 (and key (concat key yas-trigger-symbol))))))
1069 (unless (yas--template-menu-managed-by-yas-define-menu template)
1071 (yas--menu-keymap-get-create (yas--table-mode table)
1072 (mapcar #'yas--table-mode
1073 (yas--table-parents table))))
1074 (group (yas--template-group template)))
1075 ;; Remove from menu keymap
1077 (assert menu-keymap)
1078 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1080 ;; Add necessary subgroups as necessary.
1082 (dolist (subgroup group)
1083 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1084 (unless (and subgroup-keymap
1085 (keymapp subgroup-keymap))
1086 (setq subgroup-keymap (make-sparse-keymap))
1087 (define-key menu-keymap (vector (make-symbol subgroup))
1088 `(menu-item ,subgroup ,subgroup-keymap)))
1089 (setq menu-keymap subgroup-keymap)))
1091 ;; Add this entry to the keymap
1093 (define-key menu-keymap
1094 (vector (make-symbol (yas--template-uuid template)))
1095 (car (yas--template-menu-binding-pair template))))))
1097 (defun yas--namehash-templates-alist (namehash)
1098 "Return NAMEHASH as an alist."
1100 (maphash #'(lambda (k v)
1101 (push (cons k v) alist))
1105 (defun yas--fetch (table key)
1106 "Fetch templates in TABLE by KEY.
1108 Return a list of cons (NAME . TEMPLATE) where NAME is a
1109 string and TEMPLATE is a `yas--template' structure."
1110 (let* ((keyhash (yas--table-hash table))
1111 (namehash (and keyhash (gethash key keyhash))))
1113 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1116 ;;; Filtering/condition logic
1118 (defun yas--eval-condition (condition)
1125 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1129 (defun yas--filter-templates-by-condition (templates)
1130 "Filter the templates using the applicable condition.
1132 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1133 string and TEMPLATE is a `yas--template' structure.
1135 This function implements the rules described in
1136 `yas-buffer-local-condition'. See that variables documentation."
1137 (let ((requirement (yas--require-template-specific-condition-p)))
1138 (if (eq requirement 'always)
1140 (remove-if-not #'(lambda (pair)
1141 (yas--template-can-expand-p
1142 (yas--template-condition (cdr pair)) requirement))
1145 (defun yas--require-template-specific-condition-p ()
1146 "Decides if this buffer requests/requires snippet-specific
1147 conditions to filter out potential expansions."
1148 (if (eq 'always yas-buffer-local-condition)
1150 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1151 (yas--eval-condition yas-buffer-local-condition))
1152 yas-buffer-local-condition)))
1153 (when local-condition
1154 (if (eq local-condition t)
1156 (and (consp local-condition)
1157 (eq 'require-snippet-condition (car local-condition))
1158 (symbolp (cdr local-condition))
1159 (cdr local-condition)))))))
1161 (defun yas--template-can-expand-p (condition requirement)
1162 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1163 (let* ((result (or (null condition)
1164 (yas--eval-condition condition))))
1165 (cond ((eq requirement t)
1168 (eq requirement result)))))
1170 (defun yas--all-parents (mode)
1171 "Returns a list of all parent modes of MODE."
1172 (or (gethash mode yas--ancestors)
1174 (labels ((yas--all-parents-1
1176 (cond ((memq m seen)
1178 "Cyclic parenthood: mode %s has already seen as a parent of mode %s"
1182 (let* ((parents (gethash m yas--parents)))
1183 (setq seen (append seen parents))
1184 (append parents (mapcan #'yas--all-parents-1 parents)))))))
1185 (puthash mode (yas--all-parents-1 mode)
1188 (defun yas--table-templates (table)
1191 (maphash #'(lambda (key namehash)
1192 (maphash #'(lambda (name template)
1193 (push (cons name template) acc))
1195 (yas--table-hash table))
1196 (yas--filter-templates-by-condition acc))))
1198 (defun yas--current-key ()
1199 "Get the key under current position. A key is used to find
1200 the template of a snippet in the current snippet-table."
1201 (let ((start (point))
1203 (syntaxes yas-key-syntaxes)
1207 (while (and (not done) syntaxes)
1208 (setq syntax (car syntaxes))
1209 (setq syntaxes (cdr syntaxes))
1211 (skip-syntax-backward syntax)
1212 (setq start (point)))
1214 (mapcan #'(lambda (table)
1215 (yas--fetch table (buffer-substring-no-properties start end)))
1216 (yas--get-snippet-tables)))
1225 (defun yas--table-all-keys (table)
1226 "Get trigger keys of all active snippets in TABLE."
1228 (maphash #'(lambda (key namehash)
1229 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1231 (yas--table-hash table))
1234 (defun yas--table-mode (table)
1235 (intern (yas--table-name table)))
1238 ;;; Internal functions and macros:
1240 (defun yas--real-mode? (mode)
1241 "Try to find out if MODE is a real mode.
1243 The MODE bound to a function (like `c-mode') is considered real
1244 mode. Other well known mode like `ruby-mode' which is not part of
1245 Emacs might not bound to a function until it is loaded. So
1246 yasnippet keeps a list of modes like this to help the judgment."
1248 (find mode yas--known-modes)))
1250 (defun yas--eval-lisp (form)
1251 "Evaluate FORM and convert the result to string."
1252 (let ((retval (catch 'yas--exception
1258 (let ((result (eval form)))
1260 (format "%s" result))))))
1261 (error (if yas-good-grace
1262 (yas--format "elisp error! %s" (error-message-string err))
1263 (error (yas--format "elisp error: %s"
1264 (error-message-string err)))))))))
1265 (when (and (consp retval)
1266 (eq 'yas--exception (car retval)))
1267 (error (cdr retval)))
1270 (defun yas--eval-lisp-no-saves (form)
1273 (error (if yas-good-grace
1274 (yas--format "elisp error! %s" (error-message-string err))
1275 (error (yas--format "elisp error: %s"
1276 (error-message-string err)))))))
1278 (defun yas--read-lisp (string &optional nil-on-error)
1279 "Read STRING as a elisp expression and return it.
1281 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1282 return an expression that when evaluated will issue an error."
1285 (error (and (not nil-on-error)
1286 `(error (error-message-string ,err))))))
1288 (defun yas--read-keybinding (keybinding)
1289 "Read KEYBINDING as a snippet keybinding, return a vector."
1290 (when (and keybinding
1291 (not (string-match "keybinding" keybinding)))
1293 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1295 (read-kbd-macro keybinding 'need-vector))))
1298 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1299 keybinding (error-message-string err))
1302 (defvar yas-extra-modes nil
1303 "If non-nil, also lookup snippets for this/these modes.
1305 Can be a symbol or a list of symbols.
1307 This variable probably makes more sense as buffer-local, so
1308 ensure your use `make-local-variable' when you set it.")
1309 (defun yas-extra-modes ()
1310 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1311 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1313 (defun yas--table-get-create (mode)
1314 "Get or create the snippet table corresponding to MODE."
1315 (let ((table (gethash mode
1318 (setq table (yas--make-snippet-table (symbol-name mode)))
1319 (puthash mode table yas--tables)
1320 (push (cons (intern (format "yas--direct-%s" mode))
1321 (yas--table-direct-keymap table))
1322 yas--direct-keymaps))
1325 (defun yas--get-snippet-tables ()
1326 "Get snippet tables for current buffer.
1328 Return a list of `yas--table' objects. The list of modes to
1329 consider is returned by `yas--modes-to-activate'"
1331 (mapcar #'(lambda (mode-name)
1332 (gethash mode-name yas--tables))
1333 (yas--modes-to-activate))))
1335 (defun yas--menu-keymap-get-create (mode &optional parents)
1336 "Get or create the menu keymap for MODE and its PARENTS.
1338 This may very well create a plethora of menu keymaps and arrange
1339 them all in `yas--menu-table'"
1340 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1341 (puthash mode (make-sparse-keymap) yas--menu-table))))
1342 (mapc #'yas--menu-keymap-get-create parents)
1343 (define-key yas--minor-mode-menu (vector mode)
1344 `(menu-item ,(symbol-name mode) ,menu-keymap
1345 :visible (yas--show-menu-p ',mode)))
1349 (defmacro yas--called-interactively-p (&optional kind)
1350 "A backward-compatible version of `called-interactively-p'.
1352 Optional KIND is as documented at `called-interactively-p'
1353 in GNU Emacs 24.1 or higher."
1354 (if (string< emacs-version "24.1")
1355 '(called-interactively-p)
1356 `(called-interactively-p ,kind)))
1359 (defun yas--call-with-temporary-redefinitions (function
1360 &rest function-names-and-overriding-functions)
1361 (let* ((overrides (remove-if-not #'(lambda (fdef)
1362 (fboundp (first fdef)))
1363 function-names-and-overriding-functions))
1364 (definition-names (mapcar #'first overrides))
1365 (overriding-functions (mapcar #'second overrides))
1366 (saved-functions (mapcar #'symbol-function definition-names)))
1367 ;; saving all definitions before overriding anything ensures FDEFINITION
1368 ;; errors don't cause accidental permanent redefinitions.
1370 (labels ((set-fdefinitions (names functions)
1371 (loop for name in names
1373 do (fset name fn))))
1374 (set-fdefinitions definition-names overriding-functions)
1375 (unwind-protect (funcall function)
1376 (set-fdefinitions definition-names saved-functions)))))
1379 (defmacro yas--with-temporary-redefinitions (fdefinitions &rest body)
1380 ;; "Temporarily (but globally) redefine each function in FDEFINITIONS.
1381 ;; E.g.: (yas--with-temporary-redefinitions ((foo (x) ...)
1383 ;; ;; code that eventually calls foo, bar of (setf foo)
1385 `(yas--call-with-temporary-redefinitions
1387 ,@(mapcar #'(lambda (thingy)
1388 `(list ',(first thingy)
1389 (lambda ,@(rest thingy))))
1392 (put 'yas--with-temporary-redefinitions 'lisp-indent-function 1)
1393 (put 'yas--with-temporary-redefinitions 'edebug-form-spec '((&rest (defun*)) cl-declarations body))
1396 ;;; Template-related and snippet loading functions
1398 (defun yas--parse-template (&optional file)
1399 "Parse the template in the current buffer.
1401 Optional FILE is the absolute file name of the file being
1404 Optional GROUP is the group where the template is to go,
1405 otherwise we attempt to calculate it from FILE.
1407 Return a snippet-definition, i.e. a list
1409 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1411 If the buffer contains a line of \"# --\" then the contents above
1412 this line are ignored. Directives can set most of these with the syntax:
1414 # directive-name : directive-value
1416 Here's a list of currently recognized directives:
1427 (goto-char (point-min))
1428 (let* ((type 'snippet)
1430 (file-name-nondirectory file)))
1436 (yas--calculate-group file)))
1440 (if (re-search-forward "^# --\n" nil t)
1441 (progn (setq template
1442 (buffer-substring-no-properties (point)
1444 (setq bound (point))
1445 (goto-char (point-min))
1446 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1447 (when (string= "uuid" (match-string-no-properties 1))
1448 (setq uuid (match-string-no-properties 2)))
1449 (when (string= "type" (match-string-no-properties 1))
1450 (setq type (if (string= "command" (match-string-no-properties 2))
1453 (when (string= "key" (match-string-no-properties 1))
1454 (setq key (match-string-no-properties 2)))
1455 (when (string= "name" (match-string-no-properties 1))
1456 (setq name (match-string-no-properties 2)))
1457 (when (string= "condition" (match-string-no-properties 1))
1458 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1459 (when (string= "group" (match-string-no-properties 1))
1460 (setq group (match-string-no-properties 2)))
1461 (when (string= "expand-env" (match-string-no-properties 1))
1462 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1464 (when (string= "binding" (match-string-no-properties 1))
1465 (setq binding (match-string-no-properties 2)))))
1467 (buffer-substring-no-properties (point-min) (point-max))))
1468 (unless (or key binding)
1469 (setq key (and file (file-name-nondirectory file))))
1470 (when (eq type 'command)
1471 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1473 (setq group (split-string group "\\.")))
1474 (list key template name condition group expand-env file binding uuid)))
1476 (defun yas--calculate-group (file)
1477 "Calculate the group for snippet file path FILE."
1478 (let* ((dominating-dir (locate-dominating-file file
1479 ".yas-make-groups"))
1480 (extra-path (and dominating-dir
1481 (replace-regexp-in-string (concat "^"
1482 (expand-file-name dominating-dir))
1484 (expand-file-name file))))
1485 (extra-dir (and extra-path
1486 (file-name-directory extra-path)))
1487 (group (and extra-dir
1488 (replace-regexp-in-string "/"
1490 (directory-file-name extra-dir)))))
1493 (defun yas--subdirs (directory &optional filep)
1494 "Return subdirs or files of DIRECTORY according to FILEP."
1495 (remove-if (lambda (file)
1496 (or (string-match "^\\."
1497 (file-name-nondirectory file))
1498 (string-match "^#.*#$"
1499 (file-name-nondirectory file))
1501 (file-name-nondirectory file))
1503 (file-directory-p file)
1504 (not (file-directory-p file)))))
1505 (directory-files directory t)))
1507 (defun yas--make-menu-binding (template)
1508 (let ((mode (yas--table-mode (yas--template-table template))))
1509 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1511 (defun yas--expand-or-visit-from-menu (mode uuid)
1512 (let* ((table (yas--table-get-create mode))
1513 (yas--current-template (and table
1514 (gethash uuid (yas--table-uuidhash table)))))
1515 (when yas--current-template
1516 (if yas-visit-from-menu
1517 (yas--visit-snippet-file-1 yas--current-template)
1518 (let ((where (if (region-active-p)
1519 (cons (region-beginning) (region-end))
1520 (cons (point) (point)))))
1521 (yas-expand-snippet (yas--template-content yas--current-template)
1524 (yas--template-expand-env yas--current-template)))))))
1526 (defun yas--key-from-desc (text)
1527 "Return a yasnippet key from a description string TEXT."
1528 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1531 ;;; Popping up for keys and templates
1533 (defvar yas--x-pretty-prompt-templates nil
1534 "If non-nil, attempt to prompt for templates like TextMate.")
1537 (defun yas--prompt-for-template (templates &optional prompt)
1538 "Interactively choose a template from the list TEMPLATES.
1540 TEMPLATES is a list of `yas--template'.
1542 Optional PROMPT sets the prompt to use."
1545 (sort templates #'(lambda (t1 t2)
1546 (< (length (yas--template-name t1))
1547 (length (yas--template-name t2))))))
1548 (if yas--x-pretty-prompt-templates
1549 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1550 (some #'(lambda (fn)
1551 (funcall fn (or prompt "Choose a snippet: ")
1553 #'yas--template-name))
1554 yas-prompt-functions))))
1556 (defun yas--prompt-for-keys (keys &optional prompt)
1557 "Interactively choose a template key from the list KEYS.
1559 Optional PROMPT sets the prompt to use."
1561 (some #'(lambda (fn)
1562 (funcall fn (or prompt "Choose a snippet key: ") keys))
1563 yas-prompt-functions)))
1565 (defun yas--prompt-for-table (tables &optional prompt)
1566 "Interactively choose a table from the list TABLES.
1568 Optional PROMPT sets the prompt to use."
1570 (some #'(lambda (fn)
1571 (funcall fn (or prompt "Choose a snippet table: ")
1574 yas-prompt-functions)))
1576 (defun yas-x-prompt (prompt choices &optional display-fn)
1577 "Display choices in a x-window prompt."
1578 ;; FIXME: HACK: if we notice that one of the objects in choices is
1579 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1581 ;; This would be better implemented by passing CHOICES as a
1582 ;; structured tree rather than a list. Modifications would go as far
1583 ;; up as `yas--all-templates' I think.
1585 (when (and window-system choices)
1587 (let (menu d) ;; d for display
1589 (setq d (or (and display-fn (funcall display-fn c))
1592 (push (cons (concat " " d) c) menu))
1594 (push (car d) menu))))
1595 (setq menu (list prompt (push "title" menu)))
1596 (x-popup-menu (if (fboundp 'posn-at-point)
1597 (let ((x-y (posn-x-y (posn-at-point (point)))))
1598 (list (list (+ (car x-y) 10)
1606 (defun yas--x-pretty-prompt-templates (prompt templates)
1607 "Display TEMPLATES, grouping neatly by table name."
1608 (let ((organized (make-hash-table :test #'equal))
1612 (dolist (tl templates)
1613 (puthash (yas--template-table tl)
1615 (gethash (yas--template-table tl) organized))
1617 (setq more-than-one-table (> (hash-table-count organized) 1))
1618 (setq prefix (if more-than-one-table
1620 (if more-than-one-table
1621 (maphash #'(lambda (table templates)
1622 (push (yas--table-name table) menu)
1623 (dolist (tl templates)
1624 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1625 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1627 (setq menu (nreverse menu))
1628 (or (x-popup-menu (if (fboundp 'posn-at-point)
1629 (let ((x-y (posn-x-y (posn-at-point (point)))))
1630 (list (list (+ (car x-y) 10)
1634 (list prompt (push "title" menu)))
1637 (defun yas-ido-prompt (prompt choices &optional display-fn)
1638 (when (and (fboundp 'ido-completing-read)
1639 (or (>= emacs-major-version 24)
1641 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1644 (if (fboundp 'declare-function)
1645 (declare-function dropdown-list "dropdown-list")))
1647 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1648 (when (featurep 'dropdown-list)
1649 (let (formatted-choices
1653 (dolist (choice choices)
1654 (setq d (or (and display-fn (funcall display-fn choice))
1657 (push d formatted-choices)
1658 (push choice filtered-choices)))
1660 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1662 (nth n filtered-choices)
1665 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1666 (let (formatted-choices
1670 (completion-fn (or completion-fn
1671 #'completing-read)))
1672 (dolist (choice choices)
1673 (setq d (or (and display-fn (funcall display-fn choice))
1676 (push d formatted-choices)
1677 (push choice filtered-choices)))
1678 (setq chosen (and formatted-choices
1679 (funcall completion-fn prompt
1685 (let ((position (or (and chosen
1686 (position chosen formatted-choices :test #'string=))
1688 (nth position filtered-choices))))
1690 (defun yas-no-prompt (prompt choices &optional display-fn)
1694 ;;; Defining snippets
1695 ;; This consists of creating and registering `yas--template' objects in the
1699 (defun yas--define-snippets-1 (snippet snippet-table)
1700 "Helper for `yas-define-snippets'."
1701 ;; X) Calculate some more defaults on the values returned by
1702 ;; `yas--parse-template'.
1704 (let* ((file (seventh snippet))
1706 (name (or (third snippet)
1708 (file-name-directory file))))
1709 (condition (fourth snippet))
1710 (group (fifth snippet))
1711 (keybinding (yas--read-keybinding (eighth snippet)))
1712 (uuid (or (ninth snippet)
1714 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1715 (yas--make-blank-template))))
1716 ;; X) populate the template object
1718 (yas--populate-template template
1719 :table snippet-table
1721 :content (second snippet)
1724 :condition condition
1725 :expand-env (sixth snippet)
1726 :file (seventh snippet)
1727 :keybinding keybinding
1729 ;; X) Update this template in the appropriate table. This step
1730 ;; also will take care of adding the key indicators in the
1731 ;; templates menu entry, if any
1733 (yas--update-template snippet-table template)
1734 ;; X) Return the template
1739 (defun yas-define-snippets (mode snippets)
1740 "Define SNIPPETS for MODE.
1742 SNIPPETS is a list of snippet definitions, each taking the
1745 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1747 Within these, only KEY and TEMPLATE are actually mandatory.
1749 TEMPLATE might be a lisp form or a string, depending on whether
1750 this is a snippet or a snippet-command.
1752 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1753 been `yas--read-lisp'-ed and will eventually be
1754 `yas--eval-lisp'-ed.
1756 The remaining elements are strings.
1758 FILE is probably of very little use if you're programatically
1761 UUID is the snippets \"unique-id\". Loading a second snippet file
1762 with the same uuid replaced the previous snippet.
1764 You can use `yas--parse-template' to return such lists based on
1765 the current buffers contents."
1766 (let ((snippet-table (yas--table-get-create mode))
1768 (dolist (snippet snippets)
1769 (setq template (yas--define-snippets-1 snippet
1774 ;;; Loading snippets from files
1776 (defun yas--load-yas-setup-file (file)
1777 (load file 'noerror))
1779 (defun yas--define-parents (mode parents)
1780 "Add PARENTS to the list of MODE's parents."
1781 (puthash mode (remove-duplicates
1783 (gethash mode yas--parents)))
1786 (defun yas-load-directory (top-level-dir &optional use-jit)
1787 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1789 Below TOP-LEVEL-DIR each directory should be a mode name.
1791 Optional USE-JIT use jit-loading of snippets."
1792 (interactive "DSelect the root directory: ")
1793 (unless yas-snippet-dirs
1794 (setq yas-snippet-dirs top-level-dir))
1795 (dolist (dir (yas--subdirs top-level-dir))
1796 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1797 (concat dir "/dummy")))
1798 (mode-sym (car major-mode-and-parents))
1799 (parents (cdr major-mode-and-parents)))
1800 ;; Attention: The parents and the menus are already defined
1801 ;; here, even if the snippets are later jit-loaded.
1803 ;; * We need to know the parents at this point since entering a
1804 ;; given mode should jit load for its parents
1805 ;; immediately. This could be reviewed, the parents could be
1806 ;; discovered just-in-time-as well
1808 ;; * We need to create the menus here to support the `full'
1809 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1811 (yas--define-parents mode-sym parents)
1812 (yas--menu-keymap-get-create mode-sym)
1813 (let ((form `(yas--load-directory-1 ,dir
1817 (not (some #'(lambda (buffer)
1818 (with-current-buffer buffer
1819 (when (eq major-mode mode-sym)
1820 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1823 (yas--schedule-jit mode-sym form)
1825 (when (yas--called-interactively-p 'interactive)
1826 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1828 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1829 "Recursively load snippet templates from DIRECTORY."
1830 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1831 (if (and (not no-compiled-snippets)
1832 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1833 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1834 (yas--message 2 "Loading snippet files from %s" directory)
1835 (yas--load-directory-2 directory mode-sym))))
1837 (defun yas--load-directory-2 (directory mode-sym)
1838 ;; Load .yas-setup.el files wherever we find them
1840 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1841 (let* ((default-directory directory)
1843 ;; load the snippet files
1846 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1847 (when (file-readable-p file)
1848 (insert-file-contents file nil nil nil t)
1849 (push (yas--parse-template file)
1852 (yas-define-snippets mode-sym
1854 ;; now recurse to a lower level
1856 (dolist (subdir (yas--subdirs directory))
1857 (yas--load-directory-2 subdir
1860 (defun yas--load-snippet-dirs (&optional nojit)
1861 "Reload the directories listed in `yas-snippet-dirs' or
1862 prompt the user to select one."
1864 (if yas-snippet-dirs
1865 (dolist (directory (reverse (yas-snippet-dirs)))
1866 (cond ((file-directory-p directory)
1867 (yas-load-directory directory (not nojit))
1869 (yas--message 3 "Loaded %s" directory)
1870 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1872 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1873 (call-interactively 'yas-load-directory))
1876 (defun yas-reload-all (&optional interactive)
1877 "Reload all snippets and rebuild the YASnippet menu.
1879 When called interactively force immediate reload of all known
1880 snippets under `yas-snippet-dirs', otherwise use just-in-time
1885 (snippet-editing-buffers
1886 (remove-if-not #'(lambda (buffer)
1887 (with-current-buffer buffer yas--editing-template))
1889 ;; Warn if there are buffers visiting snippets, since reloading will break
1890 ;; any on-line editing of those buffers.
1892 (when snippet-editing-buffers
1894 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1895 (mapc #'kill-buffer snippet-editing-buffers)
1896 (yas--message 1 "Aborted reload...")
1898 ;; in a non-interactive use, at least set
1899 ;; `yas--editing-template' to nil, make it guess it next time around
1900 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1902 ;; Empty all snippet tables and parenting info
1904 (setq yas--tables (make-hash-table))
1905 (setq yas--parents (make-hash-table))
1906 (setq yas--ancestors (make-hash-table))
1908 ;; Before killing `yas--menu-table' use its keys to cleanup the
1909 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1910 ;; up `yas-minor-mode-map', which points to it)
1912 (maphash #'(lambda (menu-symbol keymap)
1913 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1915 ;; Now empty `yas--menu-table' as well
1916 (setq yas--menu-table (make-hash-table))
1918 ;; Cancel all pending 'yas--scheduled-jit-loads'
1920 (setq yas--scheduled-jit-loads (make-hash-table))
1922 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1923 ;; the user to select one.
1925 (setq errors (yas--load-snippet-dirs interactive))
1926 ;; Reload the direct keybindings
1928 (yas-direct-keymaps-reload)
1930 (yas--message 3 "Reloaded everything%s...%s."
1931 (if interactive "" " (snippets will load just-in-time)")
1932 (if errors " (some errors, check *Messages*)" "")))))
1934 (defun yas--load-pending-jits ()
1935 (dolist (mode (yas--modes-to-activate))
1936 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1937 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1938 (dolist (form forms)
1939 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1941 (remhash mode yas--scheduled-jit-loads))))
1943 ;; (when (<= emacs-major-version 22)
1944 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1946 (defun yas--quote-string (string)
1947 "Escape and quote STRING.
1948 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1950 (replace-regexp-in-string "[\\\"]"
1956 ;;; Snippet compilation function
1958 (defun yas--initialize ()
1959 "For backward compatibility, enable `yas-minor-mode' globally."
1960 (yas-global-mode 1))
1962 (defun yas-compile-directory (top-level-dir)
1963 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1965 This works by stubbing a few functions, then calling
1966 `yas-load-directory'."
1967 (interactive "DTop level snippet directory?")
1968 (yas--with-temporary-redefinitions
1969 ((yas--load-yas-setup-file
1971 (let ((elfile (concat file ".el")))
1972 (when (file-exists-p elfile)
1973 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1974 (insert-file-contents elfile)
1975 (goto-char (point-max))
1977 (yas-define-snippets
1979 (insert ";;; Snippet definitions:\n;;;\n")
1980 (let ((literal-snippets (list))
1982 (dolist (snippet snippets)
1983 (let ((key (first snippet))
1984 (template-content (second snippet))
1985 (name (third snippet))
1986 (condition (fourth snippet))
1987 (group (fifth snippet))
1988 (expand-env (sixth snippet))
1989 (file nil) ;; (seventh snippet)) ;; omit on purpose
1990 (binding (eighth snippet))
1991 (uuid (ninth snippet)))
2002 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
2004 (yas--load-directory-1
2005 (dir mode parents &rest ignore)
2006 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
2007 (with-temp-file output-file
2008 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
2009 (yas--load-directory-2 dir mode)
2010 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
2011 (yas-load-directory top-level-dir nil)))
2013 (defun yas-recompile-all ()
2014 "Compile every dir in `yas-snippet-dirs'."
2016 (mapc #'yas-compile-directory (yas-snippet-dirs)))
2022 (defvar yas--scheduled-jit-loads (make-hash-table)
2023 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
2025 (defun yas--schedule-jit (mode form)
2028 (gethash mode yas--scheduled-jit-loads))
2029 yas--scheduled-jit-loads))
2033 ;;; Some user level functions
2037 (message (concat "yasnippet (version "
2039 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2042 ;;; Apropos snippet menu:
2044 ;; The snippet menu keymaps are store by mode in hash table called
2045 ;; `yas--menu-table'. They are linked to the main menu in
2046 ;; `yas--menu-keymap-get-create' and are initially created empty,
2047 ;; reflecting the table hierarchy.
2049 ;; They can be populated in two mutually exclusive ways: (1) by
2050 ;; reading `yas--template-group', which in turn is populated by the "#
2051 ;; group:" directives of the snippets or the ".yas-make-groups" file
2052 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2053 ;; menu structure based on snippets uuids.
2055 ;; Both situations are handled in `yas--update-template-menu', which
2056 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2057 ;; that can tell between the two situations.
2061 ;; * if `yas-define-menu' is used it must run before
2062 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2063 ;; duplicate entries. The `yas--template' objects are created in
2064 ;; `yas-define-menu', holding nothing but the menu entry,
2065 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2066 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2067 ;; part is then stored in the menu keymap itself which make the item
2068 ;; appear to the user. These limitations could probably be revised.
2070 ;; * The `yas--template-perm-group' slot is only used in
2071 ;; `yas-describe-tables'.
2073 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2074 "Get TEMPLATE's menu binding or assign it a new one.
2076 TYPE may be `:stay', signaling this menu binding should be
2077 static in the menu."
2078 (or (yas--template-menu-binding-pair template)
2079 (let ((key (yas--template-key template))
2080 (keybinding (yas--template-keybinding template)))
2081 (setf (yas--template-menu-binding-pair template)
2082 (cons `(menu-item ,(or (yas--template-name template)
2083 (yas--template-uuid template))
2084 ,(yas--make-menu-binding template)
2087 (defun yas--template-menu-managed-by-yas-define-menu (template)
2088 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2089 (cdr (yas--template-menu-binding-pair template)))
2092 (defun yas--show-menu-p (mode)
2093 (cond ((eq yas-use-menu 'abbreviate)
2095 (mapcar #'(lambda (table)
2096 (yas--table-mode table))
2097 (yas--get-snippet-tables))))
2098 ((eq yas-use-menu 'full)
2100 ((eq yas-use-menu t)
2103 (defun yas--delete-from-keymap (keymap uuid)
2104 "Recursively delete items with UUID from KEYMAP and its submenus."
2106 ;; XXX: This used to skip any submenus named \"parent mode\"
2108 ;; First of all, recursively enter submenus, i.e. the tree is
2109 ;; searched depth first so that stale submenus can be found in the
2112 (mapc #'(lambda (item)
2113 (when (and (listp (cdr item))
2114 (keymapp (third (cdr item))))
2115 (yas--delete-from-keymap (third (cdr item)) uuid)))
2117 ;; Set the uuid entry to nil
2119 (define-key keymap (vector (make-symbol uuid)) nil)
2120 ;; Destructively modify keymap
2122 (setcdr keymap (delete-if #'(lambda (item)
2123 (or (null (cdr item))
2124 (and (keymapp (third (cdr item)))
2125 (null (cdr (third (cdr item)))))))
2128 (defun yas-define-menu (mode menu &optional omit-items)
2129 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2131 MENU is a list, its elements can be:
2133 - (yas-item UUID) : Creates an entry the snippet identified with
2134 UUID. The menu entry for a snippet thus identified is
2135 permanent, i.e. it will never move (be reordered) in the menu.
2137 - (yas-separator) : Creates a separator
2139 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2140 SUBMENU has the same form as MENU. NAME is also added to the
2141 list of groups of the snippets defined thereafter.
2143 OMIT-ITEMS is a list of snippet uuid's that will always be
2144 omitted from MODE's menu, even if they're manually loaded.
2146 This function does nothing if `yas-use-menu' is nil."
2148 (let* ((table (yas--table-get-create mode))
2149 (hash (yas--table-uuidhash table)))
2150 (yas--define-menu-1 table
2151 (yas--menu-keymap-get-create mode)
2154 (dolist (uuid omit-items)
2155 (let ((template (or (gethash uuid hash)
2156 (yas--populate-template (puthash uuid
2157 (yas--make-blank-template)
2161 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2163 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2164 "Helper for `yas-define-menu'."
2165 (dolist (e (reverse menu))
2166 (cond ((eq (first e) 'yas-item)
2167 (let ((template (or (gethash (second e) uuidhash)
2168 (yas--populate-template (puthash (second e)
2169 (yas--make-blank-template)
2172 :perm-group group-list
2173 :uuid (second e)))))
2174 (define-key menu-keymap (vector (gensym))
2175 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2176 ((eq (first e) 'yas-submenu)
2177 (let ((subkeymap (make-sparse-keymap)))
2178 (define-key menu-keymap (vector (gensym))
2179 `(menu-item ,(second e) ,subkeymap))
2180 (yas--define-menu-1 table
2184 (append group-list (list (second e))))))
2185 ((eq (first e) 'yas-separator)
2186 (define-key menu-keymap (vector (gensym))
2187 '(menu-item "----")))
2189 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2191 (defun yas--define (mode key template &optional name condition group)
2192 "Define a snippet. Expanding KEY into TEMPLATE.
2194 NAME is a description to this template. Also update the menu if
2195 `yas-use-menu' is t. CONDITION is the condition attached to
2196 this snippet. If you attach a condition to a snippet, then it
2197 will only be expanded when the condition evaluated to non-nil."
2198 (yas-define-snippets mode
2199 (list (list key template name condition group))))
2201 (defun yas-hippie-try-expand (first-time?)
2202 "Integrate with hippie expand.
2204 Just put this function in `hippie-expand-try-functions-list'."
2205 (when yas-minor-mode
2206 (if (not first-time?)
2207 (let ((yas-fallback-behavior 'return-nil))
2213 ;;; Apropos condition-cache:
2218 (defvar yas--condition-cache-timestamp nil)
2219 (defmacro yas-define-condition-cache (func doc &rest body)
2220 "Define a function FUNC with doc DOC and body BODY, BODY is
2221 executed at most once every snippet expansion attempt, to check
2222 expansion conditions.
2224 It doesn't make any sense to call FUNC programatically."
2225 `(defun ,func () ,(if (and doc
2228 "\n\nFor use in snippets' conditions. Within each
2229 snippet-expansion routine like `yas-expand', computes actual
2230 value for the first time then always returns a cached value.")
2231 (setq body (cons doc body))
2233 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2234 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2235 (cdr timestamp-and-value)
2236 (let ((new-value (progn
2239 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2242 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2243 (defun yas-expand-from-trigger-key (&optional field)
2244 "Expand a snippet before point.
2246 If no snippet expansion is possible, fall back to the behaviour
2247 defined in `yas-fallback-behavior'.
2249 Optional argument FIELD is for non-interactive use and is an
2250 object satisfying `yas--field-p' to restrict the expansion to."
2252 (setq yas--condition-cache-timestamp (current-time))
2253 (let (templates-and-pos)
2254 (unless (and yas-expand-only-for-last-commands
2255 (not (member last-command yas-expand-only-for-last-commands)))
2256 (setq templates-and-pos (if field
2258 (narrow-to-region (yas--field-start field)
2259 (yas--field-end field))
2261 (yas--current-key))))
2262 (if (and templates-and-pos
2263 (first templates-and-pos))
2264 (yas--expand-or-prompt-for-template (first templates-and-pos)
2265 (second templates-and-pos)
2266 (third templates-and-pos))
2267 (yas--fallback 'trigger-key))))
2269 (defun yas-expand-from-keymap ()
2270 "Directly expand some snippets, searching `yas--direct-keymaps'.
2272 If expansion fails, execute the previous binding for this key"
2274 (setq yas--condition-cache-timestamp (current-time))
2275 (let* ((yas--prefix current-prefix-arg)
2276 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2277 universal-argument-num-events
2279 (templates (mapcan #'(lambda (table)
2280 (yas--fetch table vec))
2281 (yas--get-snippet-tables))))
2283 (yas--expand-or-prompt-for-template templates)
2284 (let ((yas-fallback-behavior 'call-other-command))
2287 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2288 "Expand one of TEMPLATES from START to END.
2290 Prompt the user if TEMPLATES has more than one element, else
2291 expand immediately. Common gateway for
2292 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2293 (let ((yas--current-template (or (and (rest templates) ;; more than one
2294 (yas--prompt-for-template (mapcar #'cdr templates)))
2296 (when yas--current-template
2297 (yas-expand-snippet (yas--template-content yas--current-template)
2300 (yas--template-expand-env yas--current-template)))))
2302 ;; Apropos the trigger key and the fallback binding:
2304 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2305 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2306 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2307 ;; improve this explanation.
2309 (defun yas--fallback (&optional from-trigger-key-p)
2310 "Fallback after expansion has failed.
2312 Common gateway for `yas-expand-from-trigger-key' and
2313 `yas-expand-from-keymap'."
2314 (cond ((eq yas-fallback-behavior 'return-nil)
2317 ((eq yas-fallback-behavior 'call-other-command)
2318 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2319 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2320 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2321 (setq this-original-command beyond-yasnippet)
2322 (call-interactively beyond-yasnippet)))
2323 ((and (listp yas-fallback-behavior)
2324 (cdr yas-fallback-behavior)
2325 (eq 'apply (car yas-fallback-behavior)))
2326 (if (cddr yas-fallback-behavior)
2327 (apply (cadr yas-fallback-behavior)
2328 (cddr yas-fallback-behavior))
2329 (when (commandp (cadr yas-fallback-behavior))
2330 (setq this-command (cadr yas-fallback-behavior))
2331 (call-interactively (cadr yas-fallback-behavior)))))
2333 ;; also return nil if all the other fallbacks have failed
2336 (defun yas--keybinding-beyond-yasnippet ()
2338 (let* ((yas-minor-mode nil)
2339 (yas--direct-keymaps nil)
2340 (keys (this-single-command-keys)))
2341 (or (key-binding keys t)
2342 (key-binding (yas--fallback-translate-input keys) t))))
2344 (defun yas--fallback-translate-input (keys)
2345 "Emulate `read-key-sequence', at least what I think it does.
2347 Keys should be an untranslated key vector. Returns a translated
2348 vector of keys. FIXME not thoroughly tested"
2351 (while (< i (length keys))
2353 (translated local-function-key-map))
2354 (while (and (< j (length keys))
2356 (keymapp translated))
2357 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2359 (setq retval (vconcat retval (cond ((symbolp translated)
2361 ((vectorp translated)
2364 (substring keys i j)))))
2369 ;;; Utils for snippet development:
2371 (defun yas--all-templates (tables)
2372 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2374 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2375 `yas-buffer-local-condition'"
2376 (when yas-choose-tables-first
2377 (setq tables (list (yas--prompt-for-table tables))))
2379 (if yas-choose-keys-first
2380 (let ((key (yas--prompt-for-keys
2381 (mapcan #'yas--table-all-keys tables))))
2383 (mapcan #'(lambda (table)
2384 (yas--fetch table key))
2386 (remove-duplicates (mapcan #'yas--table-templates tables)
2389 (defun yas-insert-snippet (&optional no-condition)
2390 "Choose a snippet to expand, pop-up a list of choices according
2391 to `yas--prompt-function'.
2393 With prefix argument NO-CONDITION, bypass filtering of snippets
2396 (setq yas--condition-cache-timestamp (current-time))
2397 (let* ((yas-buffer-local-condition (or (and no-condition
2399 yas-buffer-local-condition))
2400 (templates (yas--all-templates (yas--get-snippet-tables)))
2401 (yas--current-template (and templates
2402 (or (and (rest templates) ;; more than one template for same key
2403 (yas--prompt-for-template templates))
2405 (where (if (region-active-p)
2406 (cons (region-beginning) (region-end))
2407 (cons (point) (point)))))
2408 (if yas--current-template
2409 (yas-expand-snippet (yas--template-content yas--current-template)
2412 (yas--template-expand-env yas--current-template))
2413 (yas--message 3 "No snippets can be inserted here!"))))
2415 (defun yas-visit-snippet-file ()
2416 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2418 Only success if selected snippet was loaded from a file. Put the
2419 visited file in `snippet-mode'."
2421 (let* ((yas-buffer-local-condition 'always)
2422 (templates (yas--all-templates (yas--get-snippet-tables)))
2423 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2424 (template (and templates
2425 (or (yas--prompt-for-template templates
2426 "Choose a snippet template to edit: ")
2430 (yas--visit-snippet-file-1 template)
2431 (message "No snippets tables active!"))))
2433 (defun yas--visit-snippet-file-1 (template)
2434 "Helper for `yas-visit-snippet-file'."
2435 (let ((file (yas--template-file template)))
2436 (cond ((and file (file-readable-p file))
2437 (find-file-other-window file)
2439 (set (make-local-variable 'yas--editing-template) template))
2441 (message "Original file %s no longer exists!" file))
2443 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2444 (let ((type 'snippet))
2445 (when (listp (yas--template-content template))
2446 (insert (format "# type: command\n"))
2447 (setq type 'command))
2448 (insert (format "# key: %s\n" (yas--template-key template)))
2449 (insert (format "# name: %s\n" (yas--template-name template)))
2450 (when (yas--template-keybinding template)
2451 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2452 (when (yas--template-expand-env template)
2453 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2454 (when (yas--template-condition template)
2455 (insert (format "# condition: %s\n" (yas--template-condition template))))
2457 (insert (if (eq type 'command)
2458 (pp-to-string (yas--template-content template))
2459 (yas--template-content template))))
2461 (set (make-local-variable 'yas--editing-template) template)))))
2463 (defun yas--guess-snippet-directories-1 (table)
2464 "Guesses possible snippet subdirectories for TABLE."
2465 (cons (yas--table-name table)
2466 (mapcan #'(lambda (parent)
2467 (yas--guess-snippet-directories-1
2469 (yas--table-parents table))))
2471 (defun yas--guess-snippet-directories (&optional table)
2472 "Try to guess suitable directories based on the current active
2473 tables (or optional TABLE).
2475 Returns a list of elements (TABLE . DIRS) where TABLE is a
2476 `yas--table' object and DIRS is a list of all possible directories
2477 where snippets of table might exist."
2478 (let ((main-dir (replace-regexp-in-string
2480 (or (first (or (yas-snippet-dirs)
2481 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2482 (tables (or (and table
2484 (yas--get-snippet-tables))))
2485 ;; HACK! the snippet table created here is actually registered!
2487 (unless (or table (gethash major-mode yas--tables))
2488 (push (yas--table-get-create major-mode)
2491 (mapcar #'(lambda (table)
2493 (mapcar #'(lambda (subdir)
2494 (concat main-dir "/" subdir))
2495 (yas--guess-snippet-directories-1 table))))
2498 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2499 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2500 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2501 (let ((candidate (first (cdr table-and-dirs))))
2502 (unless (file-writable-p (file-name-directory candidate))
2503 (error (yas--format "%s is not writable." candidate)))
2504 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2506 (if (gethash (yas--table-mode (car table-and-dirs))
2510 (or main-table-string
2512 (yas--table-name (car table-and-dirs))))
2514 (make-directory candidate 'also-make-parents)
2515 ;; create the .yas-parents file here...
2518 (defun yas-new-snippet (&optional no-template)
2519 "Pops a new buffer for writing a snippet.
2521 Expands a snippet-writing snippet, unless the optional prefix arg
2522 NO-TEMPLATE is non-nil."
2524 (let ((guessed-directories (yas--guess-snippet-directories)))
2526 (switch-to-buffer "*new snippet*")
2528 (kill-all-local-variables)
2531 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2532 (yas--table-mode (car d)))
2533 guessed-directories))
2534 (unless no-template (yas-expand-snippet yas-new-snippet-default))))
2536 (defun yas--compute-major-mode-and-parents (file)
2537 "Given FILE, find the nearest snippet directory for a given mode.
2539 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2540 representing one or more of the mode's parents.
2542 Note that MODE-SYM need not be the symbol of a real major mode,
2543 neither do the elements of PARENTS."
2544 (let* ((file-dir (and file
2545 (directory-file-name (or (some #'(lambda (special)
2546 (locate-dominating-file file special))
2550 (directory-file-name (file-name-directory file))))))
2551 (parents-file-name (concat file-dir "/.yas-parents"))
2552 (major-mode-name (and file-dir
2553 (file-name-nondirectory file-dir)))
2554 (major-mode-sym (or (and major-mode-name
2555 (intern major-mode-name))))
2556 (parents (when (file-readable-p parents-file-name)
2560 (insert-file-contents parents-file-name)
2561 (buffer-substring-no-properties (point-min)
2563 (when major-mode-sym
2564 (cons major-mode-sym (remove major-mode-sym parents)))))
2566 (defvar yas--editing-template nil
2567 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2569 (defvar yas--current-template nil
2570 "Holds the current template being expanded into a snippet.")
2572 (defvar yas--guessed-modes nil
2573 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2575 (defun yas--read-table ()
2576 "Ask user for a snippet table, help with some guessing."
2577 (let ((prompt (if (and (featurep 'ido)
2579 'ido-completing-read 'completing-read)))
2580 (unless yas--guessed-modes
2581 (set (make-local-variable 'yas--guessed-modes)
2582 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2584 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2585 (if yas--guessed-modes
2586 (first yas--guessed-modes)
2588 (mapcar #'symbol-name yas--guessed-modes)
2593 (if (first yas--guessed-modes)
2594 (symbol-name (first yas--guessed-modes)))))))
2596 (defun yas-load-snippet-buffer (table &optional interactive)
2597 "Parse and load current buffer's snippet definition into TABLE.
2599 TABLE is a symbol naming a passed to `yas--table-get-create'.
2601 When called interactively, prompt for the table name and
2602 whether (and where) to save the snippet, then quit the window."
2603 (interactive (list (yas--read-table) t))
2605 ;; We have `yas--editing-template', this buffer's content comes from a
2606 ;; template which is already loaded and neatly positioned,...
2608 (yas--editing-template
2609 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2610 (yas--template-table yas--editing-template)))
2611 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2612 ;; value from `yas--compute-major-mode-and-parents'
2615 (unless yas--guessed-modes
2616 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2617 (let* ((table (yas--table-get-create table)))
2618 (set (make-local-variable 'yas--editing-template)
2619 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2622 (when (and interactive
2624 ;; Only offer to save this if it looks like a library or new
2625 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2626 ;; which is not the first, or from an unwritable file)
2628 (not (yas--template-file yas--editing-template))
2629 (not (file-writable-p (yas--template-file yas--editing-template)))
2630 (and (listp yas-snippet-dirs)
2631 (second yas-snippet-dirs)
2632 (not (string-match (expand-file-name (first yas-snippet-dirs))
2633 (yas--template-file yas--editing-template)))))
2634 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2635 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2637 (yas--make-directory-maybe option))))
2639 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2640 (file-name-nondirectory (yas--template-file yas--editing-template)))
2641 (yas--template-name yas--editing-template))))
2642 (write-file (concat chosen "/"
2643 (read-from-minibuffer (format "File name to create in %s? " chosen)
2644 default-file-name)))
2645 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2647 (yas--message 3 "Snippet \"%s\" loaded for %s."
2648 (yas--template-name yas--editing-template)
2649 (yas--table-name (yas--template-table yas--editing-template)))
2650 (quit-window interactive)))
2652 (defun yas-tryout-snippet (&optional debug)
2653 "Test current buffer's snippet template in other buffer."
2655 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2656 (parsed (yas--parse-template))
2657 (test-mode (or (and (car major-mode-and-parent)
2658 (fboundp (car major-mode-and-parent))
2659 (car major-mode-and-parent))
2660 (first yas--guessed-modes)
2661 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2662 (yas--current-template
2665 (yas--populate-template (yas--make-blank-template)
2666 :table nil ;; no tables for ephemeral snippets
2668 :content (second parsed)
2669 :name (third parsed)
2670 :expand-env (sixth parsed)))))
2671 (cond (yas--current-template
2672 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2673 (kill-buffer (get-buffer-create buffer-name))
2674 (switch-to-buffer (get-buffer-create buffer-name))
2675 (setq buffer-undo-list nil)
2676 (condition-case nil (funcall test-mode) (error nil))
2678 (setq buffer-read-only nil)
2679 (yas-expand-snippet (yas--template-content yas--current-template)
2682 (yas--template-expand-env yas--current-template))
2684 (require 'yasnippet-debug nil t))
2685 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2687 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2689 (defun yas-active-keys ()
2690 "Return all active trigger keys for current buffer and point."
2692 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2695 (defun yas--template-fine-group (template)
2696 (car (last (or (yas--template-group template)
2697 (yas--template-perm-group template)))))
2699 (defun yas-describe-tables (&optional choose)
2700 "Display snippets for each table."
2702 (let* ((by-name-hash (and choose
2703 (y-or-n-p "Show by namehash? ")))
2704 (buffer (get-buffer-create "*YASnippet tables*"))
2705 (active-tables (yas--get-snippet-tables))
2706 (remain-tables (let ((all))
2707 (maphash #'(lambda (k v)
2708 (unless (find v active-tables)
2712 (table-lists (list active-tables remain-tables))
2713 (original-buffer (current-buffer))
2715 (yas--condition-cache-timestamp (current-time)))
2716 (with-current-buffer buffer
2717 (setq buffer-read-only nil)
2719 (cond ((not by-name-hash)
2720 (insert "YASnippet tables: \n")
2721 (while (and table-lists
2723 (dolist (table (car table-lists))
2724 (yas--describe-pretty-table table original-buffer))
2725 (setq table-lists (cdr table-lists))
2727 (yas--create-snippet-xrefs)
2728 (display-buffer buffer)
2729 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2730 (yas--create-snippet-xrefs)
2734 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2735 (dolist (table (append active-tables remain-tables))
2736 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2738 (maphash #'(lambda (k v)
2740 (yas--table-hash table))
2742 (insert (format " key %s maps snippets: %s\n" key
2744 (maphash #'(lambda (k v)
2746 (gethash key (yas--table-hash table)))
2749 (setq buffer-read-only t))
2750 (display-buffer buffer)))
2752 (defun yas--describe-pretty-table (table &optional original-buffer)
2753 (insert (format "\nSnippet table `%s'"
2754 (yas--table-name table)))
2755 (if (yas--table-parents table)
2756 (insert (format " parents: %s\n"
2757 (mapcar #'yas--table-name
2758 (yas--table-parents table))))
2760 (insert (make-string 100 ?-) "\n")
2761 (insert "group state name key binding\n")
2762 (let ((groups-hash (make-hash-table :test #'equal)))
2763 (maphash #'(lambda (k v)
2764 (let ((group (or (yas--template-fine-group v)
2766 (when (yas--template-name v)
2768 (cons v (gethash group groups-hash))
2770 (yas--table-uuidhash table))
2772 #'(lambda (group templates)
2773 (setq group (truncate-string-to-width group 25 0 ? "..."))
2774 (insert (make-string 100 ?-) "\n")
2775 (dolist (p templates)
2776 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2780 (setq group (make-string (length group) ? ))))
2781 (condition-string (let ((condition (yas--template-condition p)))
2784 (with-current-buffer original-buffer
2785 (if (yas--eval-condition condition)
2790 (insert condition-string " ")
2792 (if (string-match "\\.\\.\\.$" name)
2796 (insert (truncate-string-to-width (or (yas--template-key p) "")
2798 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2805 ;;; User convenience functions, for using in snippet definitions
2807 (defvar yas-modified-p nil
2808 "Non-nil if field has been modified by user or transformation.")
2810 (defvar yas-moving-away-p nil
2811 "Non-nil if user is about to exit field.")
2813 (defvar yas-text nil
2814 "Contains current field text.")
2816 (defun yas-substr (str pattern &optional subexp)
2817 "Search PATTERN in STR and return SUBEXPth match.
2819 If found, the content of subexp group SUBEXP (default 0) is
2820 returned, or else the original STR will be returned."
2821 (let ((grp (or subexp 0)))
2823 (if (string-match pattern str)
2824 (match-string-no-properties grp str)
2827 (defun yas-choose-value (&rest possibilities)
2828 "Prompt for a string in POSSIBILITIES and return it.
2830 The last element of POSSIBILITIES may be a list of strings."
2831 (unless (or yas-moving-away-p
2833 (setq possibilities (nreverse possibilities))
2834 (setq possibilities (if (listp (car possibilities))
2835 (append (reverse (car possibilities)) (rest possibilities))
2837 (some #'(lambda (fn)
2838 (funcall fn "Choose: " possibilities))
2839 yas-prompt-functions)))
2841 (defun yas-key-to-value (alist)
2842 (unless (or yas-moving-away-p
2844 (let ((key (read-key-sequence "")))
2846 (or (cdr (find key alist :key #'car :test #'string=))
2849 (defun yas-throw (text)
2850 "Throw a yas--exception with TEXT as the reason."
2851 (throw 'yas--exception (cons 'yas--exception text)))
2853 (defun yas-verify-value (possibilities)
2854 "Verify that the current field value is in POSSIBILITIES.
2856 Otherwise throw exception."
2857 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2858 (yas-throw (yas--format "Field only allows %s" possibilities))))
2860 (defun yas-field-value (number)
2861 "Get the string for field with NUMBER.
2863 Use this in primary and mirror transformations to tget."
2864 (let* ((snippet (car (yas--snippets-at-point)))
2866 (yas--snippet-find-field snippet number))))
2868 (yas--field-text-for-display field))))
2871 "Return `yas-text' if that exists and is non-empty, else nil."
2873 (not (string= "" yas-text)))
2876 (defun yas-selected-text ()
2877 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2878 (if (and yas-selected-text
2879 (not (string= "" yas-selected-text)))
2882 (defun yas--get-field-once (number &optional transform-fn)
2883 (unless yas-modified-p
2885 (funcall transform-fn (yas-field-value number))
2886 (yas-field-value number))))
2888 (defun yas-default-from-field (number)
2889 (unless yas-modified-p
2890 (yas-field-value number)))
2892 (defun yas-inside-string ()
2893 "Return non-nil if the point is inside a string according to font-lock."
2894 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2896 (defun yas-unimplemented (&optional missing-feature)
2897 (if yas--current-template
2898 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2901 (yas--visit-snippet-file-1 yas--current-template))
2902 (message "No implementation. Missing %s" (or missing-feature "something"))))
2905 ;;; Snippet expansion and field management
2907 (defvar yas--active-field-overlay nil
2908 "Overlays the currently active field.")
2910 (defvar yas--field-protection-overlays nil
2911 "Two overlays protect the current active field.")
2913 (defconst yas--prefix nil
2914 "A prefix argument for expansion direct from keybindings.")
2916 (defvar yas-selected-text nil
2917 "The selected region deleted on the last snippet expansion.")
2919 (defvar yas--start-column nil
2920 "The column where the snippet expansion started.")
2922 (make-variable-buffer-local 'yas--active-field-overlay)
2923 (make-variable-buffer-local 'yas--field-protection-overlays)
2924 (put 'yas--active-field-overlay 'permanent-local t)
2925 (put 'yas--field-protection-overlays 'permanent-local t)
2927 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2933 (id (yas--snippet-next-id) :read-only t)
2934 (control-overlay nil)
2936 ;; stacked expansion: the `previous-active-field' slot saves the
2937 ;; active field where the child expansion took place
2938 previous-active-field
2941 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2944 NUMBER is the field number.
2945 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2946 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2947 MIRRORS is a list of `yas--mirror's
2948 TRANSFORM is a lisp form.
2949 MODIFIED-P is a boolean set to true once user inputs text.
2950 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2961 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2964 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2965 TRANSFORM is a lisp form.
2966 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2967 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2968 DEPTH is a count of how many nested mirrors can affect this mirror"
2975 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2979 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2980 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2982 If there is no transform for ht field, return nil.
2984 If there is a transform but it returns nil, return the empty
2985 string iff EMPTY-ON-NIL-P is true."
2986 (let* ((yas-text (yas--field-text-for-display field))
2988 (yas-modified-p (yas--field-modified-p field))
2989 (yas-moving-away-p nil)
2990 (transform (if (yas--mirror-p field-or-mirror)
2991 (yas--mirror-transform field-or-mirror)
2992 (yas--field-transform field-or-mirror)))
2993 (start-point (if (yas--mirror-p field-or-mirror)
2994 (yas--mirror-start field-or-mirror)
2995 (yas--field-start field-or-mirror)))
2996 (transformed (and transform
2998 (goto-char start-point)
2999 (let ((ret (yas--eval-lisp transform)))
3000 (or ret (and empty-on-nil-p "")))))))
3003 (defsubst yas--replace-all (from to &optional text)
3004 "Replace all occurrences from FROM to TO.
3006 With optional string TEXT do it in that string."
3008 (replace-regexp-in-string (regexp-quote from) to text t t)
3009 (goto-char (point-min))
3010 (while (search-forward from nil t)
3011 (replace-match to t t text))))
3013 (defun yas--snippet-find-field (snippet number)
3014 (find-if #'(lambda (field)
3015 (eq number (yas--field-number field)))
3016 (yas--snippet-fields snippet)))
3018 (defun yas--snippet-sort-fields (snippet)
3019 "Sort the fields of SNIPPET in navigation order."
3020 (setf (yas--snippet-fields snippet)
3021 (sort (yas--snippet-fields snippet)
3022 #'yas--snippet-field-compare)))
3024 (defun yas--snippet-field-compare (field1 field2)
3025 "Compare FIELD1 and FIELD2.
3027 The field with a number is sorted first. If they both have a
3028 number, compare through the number. If neither have, compare
3029 through the field's start point"
3030 (let ((n1 (yas--field-number field1))
3031 (n2 (yas--field-number field2)))
3034 (or (zerop n2) (and (not (zerop n1))
3039 (< (yas--field-start field1)
3040 (yas--field-start field2))))))
3042 (defun yas--field-probably-deleted-p (snippet field)
3043 "Guess if SNIPPET's FIELD should be skipped."
3045 ;; field must be zero length
3047 (zerop (- (yas--field-start field) (yas--field-end field)))
3050 ;; 1) is a nested field and it's been modified
3052 (and (yas--field-parent-field field)
3053 (yas--field-modified-p field))
3054 ;; 2) ends just before the snippet end
3056 (and (eq field (car (last (yas--snippet-fields snippet))))
3057 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3058 ;; the field numbered 0, just before the exit marker, should
3061 (not (zerop (yas--field-number field)))))
3063 (defun yas--snippets-at-point (&optional all-snippets)
3064 "Return a sorted list of snippets at point.
3066 The most recently-inserted snippets are returned first."
3068 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3069 (overlay-get ov 'yas--snippet))
3071 (overlays-in (point-min) (point-max))
3072 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3074 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3076 (defun yas-next-field-or-maybe-expand ()
3077 "Try to expand a snippet at a key before point.
3079 Otherwise delegate to `yas-next-field'."
3081 (if yas-triggers-in-field
3082 (let ((yas-fallback-behavior 'return-nil)
3083 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3085 (unless (yas-expand-from-trigger-key active-field)
3089 (defun yas-next-field (&optional arg)
3090 "Navigate to the ARGth next field.
3092 If there's none, exit the snippet."
3096 (snippet (first (yas--snippets-at-point)))
3097 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3098 (live-fields (remove-if #'(lambda (field)
3099 (and (not (eq field active-field))
3100 (yas--field-probably-deleted-p snippet field)))
3101 (yas--snippet-fields snippet)))
3102 (active-field-pos (position active-field live-fields))
3103 (target-pos (and active-field-pos (+ arg active-field-pos)))
3104 (target-field (and target-pos (nth target-pos live-fields))))
3105 ;; First check if we're moving out of a field with a transform
3107 (when (and active-field
3108 (yas--field-transform active-field))
3109 (let* ((yas-moving-away-p t)
3110 (yas-text (yas--field-text-for-display active-field))
3112 (yas-modified-p (yas--field-modified-p active-field)))
3113 ;; primary field transform: exit call to field-transform
3114 (yas--eval-lisp (yas--field-transform active-field))))
3115 ;; Now actually move...
3116 (cond ((and target-pos (>= target-pos (length live-fields)))
3117 (yas-exit-snippet snippet))
3119 (yas--move-to-field snippet target-field))
3123 (defun yas--place-overlays (snippet field)
3124 "Correctly place overlays for SNIPPET's FIELD."
3125 (yas--make-move-field-protection-overlays snippet field)
3126 (yas--make-move-active-field-overlay snippet field))
3128 (defun yas--move-to-field (snippet field)
3129 "Update SNIPPET to move to field FIELD.
3131 Also create some protection overlays"
3132 (goto-char (yas--field-start field))
3133 (yas--place-overlays snippet field)
3134 (overlay-put yas--active-field-overlay 'yas--field field)
3135 (let ((number (yas--field-number field)))
3136 ;; check for the special ${0: ...} field
3137 (if (and number (zerop number))
3139 (set-mark (yas--field-end field))
3140 (setf (yas--snippet-force-exit snippet)
3141 (or (yas--field-transform field)
3143 ;; make this field active
3144 (setf (yas--snippet-active-field snippet) field)
3145 ;; primary field transform: first call to snippet transform
3146 (unless (yas--field-modified-p field)
3147 (if (yas--field-update-display field snippet)
3148 (yas--update-mirrors snippet)
3149 (setf (yas--field-modified-p field) nil))))))
3151 (defun yas-prev-field ()
3152 "Navigate to prev field. If there's none, exit the snippet."
3154 (yas-next-field -1))
3156 (defun yas-abort-snippet (&optional snippet)
3158 (let ((snippet (or snippet
3159 (car (yas--snippets-at-point)))))
3161 (setf (yas--snippet-force-exit snippet) t))))
3163 (defun yas-exit-snippet (snippet)
3164 "Goto exit-marker of SNIPPET."
3165 (interactive (list (first (yas--snippets-at-point))))
3167 (setf (yas--snippet-force-exit snippet) t)
3168 (goto-char (if (yas--snippet-exit snippet)
3169 (yas--exit-marker (yas--snippet-exit snippet))
3170 (overlay-end (yas--snippet-control-overlay snippet))))))
3172 (defun yas-exit-all-snippets ()
3173 "Exit all snippets."
3175 (mapc #'(lambda (snippet)
3176 (yas-exit-snippet snippet)
3177 (yas--check-commit-snippet))
3178 (yas--snippets-at-point 'all-snippets)))
3181 ;;; Some low level snippet-routines:
3183 (defmacro yas--inhibit-overlay-hooks (&rest body)
3184 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3185 (declare (indent 0))
3186 `(let ((yas--inhibit-overlay-hooks t))
3189 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3190 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3192 (defun yas--commit-snippet (snippet)
3193 "Commit SNIPPET, but leave point as it is.
3195 This renders the snippet as ordinary text."
3197 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3199 ;; Save the end of the moribund snippet in case we need to revive it
3200 ;; its original expansion.
3202 (when (and control-overlay
3203 (overlay-buffer control-overlay))
3204 (setq yas-snippet-beg (overlay-start control-overlay))
3205 (setq yas-snippet-end (overlay-end control-overlay))
3206 (delete-overlay control-overlay))
3208 (yas--inhibit-overlay-hooks
3209 (when yas--active-field-overlay
3210 (delete-overlay yas--active-field-overlay))
3211 (when yas--field-protection-overlays
3212 (mapc #'delete-overlay yas--field-protection-overlays)))
3214 ;; stacked expansion: if the original expansion took place from a
3215 ;; field, make sure we advance it here at least to
3216 ;; `yas-snippet-end'...
3218 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3219 (when (and yas-snippet-end previous-field)
3220 (yas--advance-end-maybe previous-field yas-snippet-end)))
3222 ;; Convert all markers to points,
3224 (yas--markers-to-points snippet)
3226 ;; Take care of snippet revival
3228 (if yas-snippet-revival
3229 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3231 ;; Dismember the snippet... this is useful if we get called
3232 ;; again from `yas--take-care-of-redo'....
3233 (setf (yas--snippet-fields snippet) nil)))
3235 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3237 (defun yas--safely-run-hooks (hook-var)
3238 (condition-case error
3239 (run-hooks hook-var)
3241 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3244 (defun yas--check-commit-snippet ()
3245 "Checks if point exited the currently active field of the snippet.
3247 If so cleans up the whole snippet up."
3248 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3249 (snippets-left snippets)
3250 (snippet-exit-transform))
3251 (dolist (snippet snippets)
3252 (let ((active-field (yas--snippet-active-field snippet)))
3253 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3254 (cond ((or snippet-exit-transform
3255 (not (and active-field (yas--field-contains-point-p active-field))))
3256 (setq snippets-left (delete snippet snippets-left))
3257 (setf (yas--snippet-force-exit snippet) nil)
3258 (yas--commit-snippet snippet))
3260 (or (not yas--active-field-overlay)
3261 (not (overlay-buffer yas--active-field-overlay))))
3263 ;; stacked expansion: this case is mainly for recent
3264 ;; snippet exits that place us back int the field of
3268 (yas--move-to-field snippet active-field)
3269 (yas--update-mirrors snippet)))
3272 (unless (or (null snippets) snippets-left)
3273 (if snippet-exit-transform
3274 (yas--eval-lisp-no-saves snippet-exit-transform))
3275 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3277 ;; Apropos markers-to-points:
3279 ;; This was found useful for performance reasons, so that an
3280 ;; excessive number of live markers aren't kept around in the
3281 ;; `buffer-undo-list'. However, in `markers-to-points', the
3282 ;; set-to-nil markers can't simply be discarded and replaced with
3283 ;; fresh ones in `points-to-markers'. The original marker that was
3284 ;; just set to nil has to be reused.
3286 ;; This shouldn't bring horrible problems with undo/redo, but it
3289 (defun yas--markers-to-points (snippet)
3290 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3291 where POINT is the original position of the marker and MARKER is
3292 the original marker object with the position set to nil."
3293 (dolist (field (yas--snippet-fields snippet))
3294 (let ((start (marker-position (yas--field-start field)))
3295 (end (marker-position (yas--field-end field))))
3296 (set-marker (yas--field-start field) nil)
3297 (set-marker (yas--field-end field) nil)
3298 (setf (yas--field-start field) (cons start (yas--field-start field)))
3299 (setf (yas--field-end field) (cons end (yas--field-end field))))
3300 (dolist (mirror (yas--field-mirrors field))
3301 (let ((start (marker-position (yas--mirror-start mirror)))
3302 (end (marker-position (yas--mirror-end mirror))))
3303 (set-marker (yas--mirror-start mirror) nil)
3304 (set-marker (yas--mirror-end mirror) nil)
3305 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3306 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3307 (let ((snippet-exit (yas--snippet-exit snippet)))
3309 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3310 (set-marker (yas--exit-marker snippet-exit) nil)
3311 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3313 (defun yas--points-to-markers (snippet)
3314 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3316 This is done by setting MARKER to POINT with `set-marker'."
3317 (dolist (field (yas--snippet-fields snippet))
3318 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3319 (car (yas--field-start field))))
3320 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3321 (car (yas--field-end field))))
3322 (dolist (mirror (yas--field-mirrors field))
3323 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3324 (car (yas--mirror-start mirror))))
3325 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3326 (car (yas--mirror-end mirror))))))
3327 (let ((snippet-exit (yas--snippet-exit snippet)))
3329 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3330 (car (yas--exit-marker snippet-exit)))))))
3332 (defun yas--field-contains-point-p (field &optional point)
3333 (let ((point (or point
3335 (and (>= point (yas--field-start field))
3336 (<= point (yas--field-end field)))))
3338 (defun yas--field-text-for-display (field)
3339 "Return the propertized display text for field FIELD."
3340 (buffer-substring (yas--field-start field) (yas--field-end field)))
3342 (defun yas--undo-in-progress ()
3343 "True if some kind of undo is in progress."
3344 (or undo-in-progress
3345 (eq this-command 'undo)
3346 (eq this-command 'redo)))
3348 (defun yas--make-control-overlay (snippet start end)
3349 "Creates the control overlay that surrounds the snippet and
3351 (let ((overlay (make-overlay start
3356 (overlay-put overlay 'keymap yas-keymap)
3357 (overlay-put overlay 'priority 100)
3358 (overlay-put overlay 'yas--snippet snippet)
3361 (defun yas-skip-and-clear-or-delete-char (&optional field)
3362 "Clears unmodified field if at field start, skips to next tab.
3364 Otherwise deletes a character normally by calling `delete-char'."
3366 (let ((field (or field
3367 (and yas--active-field-overlay
3368 (overlay-buffer yas--active-field-overlay)
3369 (overlay-get yas--active-field-overlay 'yas--field)))))
3371 (not (yas--field-modified-p field))
3372 (eq (point) (marker-position (yas--field-start field))))
3373 (yas--skip-and-clear field)
3376 (call-interactively 'delete-char)))))
3378 (defun yas--skip-and-clear (field)
3379 "Deletes the region of FIELD and sets it's modified state to t."
3380 ;; Just before skipping-and-clearing the field, mark its children
3381 ;; fields as modified, too. If the children have mirrors-in-fields
3382 ;; this prevents them from updating erroneously (we're skipping and
3385 (yas--mark-this-and-children-modified field)
3386 (delete-region (yas--field-start field) (yas--field-end field)))
3388 (defun yas--mark-this-and-children-modified (field)
3389 (setf (yas--field-modified-p field) t)
3390 (let ((fom (yas--field-next field)))
3392 (yas--fom-parent-field fom))
3393 (when (and (eq (yas--fom-parent-field fom) field)
3395 (yas--mark-this-and-children-modified fom))
3396 (setq fom (yas--fom-next fom)))))
3398 (defun yas--make-move-active-field-overlay (snippet field)
3399 "Place the active field overlay in SNIPPET's FIELD.
3401 Move the overlay, or create it if it does not exit."
3402 (if (and yas--active-field-overlay
3403 (overlay-buffer yas--active-field-overlay))
3404 (move-overlay yas--active-field-overlay
3405 (yas--field-start field)
3406 (yas--field-end field))
3407 (setq yas--active-field-overlay
3408 (make-overlay (yas--field-start field)
3409 (yas--field-end field)
3411 (overlay-put yas--active-field-overlay 'priority 100)
3412 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3413 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3414 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3415 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3416 '(yas--on-field-overlay-modification))
3417 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3418 '(yas--on-field-overlay-modification))))
3420 (defvar yas--inhibit-overlay-hooks nil
3421 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3423 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3424 "Clears the field and updates mirrors, conditionally.
3426 Only clears the field if it hasn't been modified and it point it
3427 at field start. This hook doesn't do anything if an undo is in
3429 (unless (or yas--inhibit-overlay-hooks
3430 (yas--undo-in-progress))
3431 (let* ((field (overlay-get overlay 'yas--field))
3432 (number (and field (yas--field-number field)))
3433 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3435 (yas--advance-end-maybe field (overlay-end overlay))
3437 (yas--field-update-display field snippet))
3438 (yas--update-mirrors snippet))
3440 (when (and (not after?)
3441 (not (yas--field-modified-p field))
3442 (eq (point) (if (markerp (yas--field-start field))
3443 (marker-position (yas--field-start field))
3444 (yas--field-start field))))
3445 (yas--skip-and-clear field))
3446 (setf (yas--field-modified-p field) t))))))
3448 ;;; Apropos protection overlays:
3450 ;; These exist for nasty users who will try to delete parts of the
3451 ;; snippet outside the active field. Actual protection happens in
3452 ;; `yas--on-protection-overlay-modification'.
3454 ;; Currently this signals an error which inhibits the command. For
3455 ;; commands that move point (like `kill-line'), point is restored in
3456 ;; the `yas--post-command-handler' using a global
3457 ;; `yas--protection-violation' variable.
3459 ;; Alternatively, I've experimented with an implementation that
3460 ;; commits the snippet before actually calling `this-command'
3461 ;; interactively, and then signals an error, which is ignored. but
3462 ;; blocks all other million modification hooks. This presented some
3463 ;; problems with stacked expansion.
3465 (defun yas--make-move-field-protection-overlays (snippet field)
3466 "Place protection overlays surrounding SNIPPET's FIELD.
3468 Move the overlays, or create them if they do not exit."
3469 (let ((start (yas--field-start field))
3470 (end (yas--field-end field)))
3471 ;; First check if the (1+ end) is contained in the buffer,
3472 ;; otherwise we'll have to do a bit of cheating and silently
3473 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3474 ;; when using stacked expansion
3476 (when (< (buffer-size) end)
3478 (yas--inhibit-overlay-hooks
3479 (goto-char (point-max))
3481 ;; go on to normal overlay creation/moving
3483 (cond ((and yas--field-protection-overlays
3484 (every #'overlay-buffer yas--field-protection-overlays))
3485 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3486 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3488 (setq yas--field-protection-overlays
3489 (list (make-overlay (1- start) start nil t nil)
3490 (make-overlay end (1+ end) nil t nil)))
3491 (dolist (ov yas--field-protection-overlays)
3492 (overlay-put ov 'face 'yas--field-debug-face)
3493 (overlay-put ov 'yas--snippet snippet)
3494 ;; (overlay-put ov 'evaporate t)
3495 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3497 (defvar yas--protection-violation nil
3498 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3500 Functions in the `post-command-hook', for example
3501 `yas--post-command-handler' can check it and reset its value to
3502 nil. The variables value is the point where the violation
3505 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3506 "Signals a snippet violation, then issues error.
3508 The error should be ignored in `debug-ignored-errors'"
3509 (unless yas--inhibit-overlay-hooks
3510 (cond ((not (or after?
3511 (yas--undo-in-progress)))
3512 (setq yas--protection-violation (point))
3513 (error "Exit the snippet first!")))))
3515 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3518 ;;; Snippet expansion and "stacked" expansion:
3520 ;; Stacked expansion is when you try to expand a snippet when already
3521 ;; inside a snippet expansion.
3523 ;; The parent snippet does not run its fields modification hooks
3524 ;; (`yas--on-field-overlay-modification' and
3525 ;; `yas--on-protection-overlay-modification') while the child snippet
3526 ;; is active. This means, among other things, that the mirrors of the
3527 ;; parent snippet are not updated, this only happening when one exits
3528 ;; the child snippet.
3530 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3531 ;; bits of code in `yas-expand-snippet' and
3532 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3535 ;; This was thought to be safer in an undo/redo perspective, but
3536 ;; maybe the correct implementation is to make the globals
3537 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3538 ;; snippet-local and be active even while the child snippet is
3539 ;; running. This would mean a lot of overlay modification hooks
3540 ;; running, but if managed correctly (including overlay priorities)
3541 ;; they should account for all situations...
3543 (defun yas-expand-snippet (content &optional start end expand-env)
3544 "Expand snippet CONTENT at current point.
3546 Text between START and END will be deleted before inserting
3547 template. EXPAND-ENV is are let-style variable to value bindings
3548 considered when expanding the snippet."
3549 (run-hooks 'yas-before-expand-snippet-hook)
3552 (let* ((yas-selected-text (or yas-selected-text
3553 (and (region-active-p)
3554 (buffer-substring-no-properties (region-beginning)
3557 (and (region-active-p)
3561 (and (region-active-p)
3564 (to-delete (and start
3566 (buffer-substring-no-properties start end)))
3569 (setq yas--indent-original-column (current-column))
3570 ;; Delete the region to delete, this *does* get undo-recorded.
3572 (when (and to-delete
3574 (delete-region start end))
3576 (cond ((listp content)
3577 ;; x) This is a snippet-command
3579 (yas--eval-lisp-no-saves content))
3581 ;; x) This is a snippet-snippet :-)
3583 ;; Narrow the region down to the content, shoosh the
3584 ;; `buffer-undo-list', and create the snippet, the new
3585 ;; snippet updates its mirrors once, so we are left with
3586 ;; some plain text. The undo action for deleting this
3587 ;; plain text will get recorded at the end.
3589 ;; stacked expansion: also shoosh the overlay modification hooks
3591 (narrow-to-region start start)
3592 (let ((buffer-undo-list t))
3593 ;; snippet creation might evaluate users elisp, which
3594 ;; might generate errors, so we have to be ready to catch
3595 ;; them mostly to make the undo information
3597 (setq yas--start-column (save-restriction (widen) (current-column)))
3598 (yas--inhibit-overlay-hooks
3601 (eval `(let* ,expand-env
3603 (yas--snippet-create (point-min) (point-max))))
3605 (yas--snippet-create (point-min) (point-max)))))))
3607 ;; stacked-expansion: This checks for stacked expansion, save the
3608 ;; `yas--previous-active-field' and advance its boundary.
3610 (let ((existing-field (and yas--active-field-overlay
3611 (overlay-buffer yas--active-field-overlay)
3612 (overlay-get yas--active-field-overlay 'yas--field))))
3613 (when existing-field
3614 (setf (yas--snippet-previous-active-field snippet) existing-field)
3615 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3617 ;; Exit the snippet immediately if no fields
3619 (unless (yas--snippet-fields snippet)
3620 (yas-exit-snippet snippet))
3622 ;; Push two undo actions: the deletion of the inserted contents of
3623 ;; the new snippet (without the "key") followed by an apply of
3624 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3626 ;; A small exception, if `yas-also-auto-indent-first-line'
3627 ;; is t and `yas--indent' decides to indent the line to a
3628 ;; point before the actual expansion point, undo would be
3629 ;; messed up. We call the early point "newstart"". case,
3630 ;; and attempt to fix undo.
3632 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3633 (end (overlay-end (yas--snippet-control-overlay snippet))))
3634 (when (< newstart start)
3635 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3636 (push (cons newstart end) buffer-undo-list)
3637 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3639 ;; Now, schedule a move to the first field
3641 (let ((first-field (car (yas--snippet-fields snippet))))
3643 (sit-for 0) ;; fix issue 125
3644 (yas--move-to-field snippet first-field)))
3645 (yas--message 3 "snippet expanded.")
3648 (defun yas--take-care-of-redo (beg end snippet)
3649 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3651 Meant to exit in the `buffer-undo-list'."
3652 ;; slightly optimize: this action is only needed for snippets with
3653 ;; at least one field
3654 (when (yas--snippet-fields snippet)
3655 (yas--commit-snippet snippet)))
3657 (defun yas--snippet-revive (beg end snippet)
3658 "Revives SNIPPET and creates a control overlay from BEG to END.
3660 BEG and END are, we hope, the original snippets boundaries. All
3661 the markers/points exiting existing inside SNIPPET should point
3662 to their correct locations *at the time the snippet is revived*.
3664 After revival, push the `yas--take-care-of-redo' in the
3666 ;; Reconvert all the points to markers
3668 (yas--points-to-markers snippet)
3669 ;; When at least one editable field existed in the zombie snippet,
3670 ;; try to revive the whole thing...
3672 (let ((target-field (or (yas--snippet-active-field snippet)
3673 (car (yas--snippet-fields snippet)))))
3675 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3676 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3678 (yas--move-to-field snippet target-field)
3680 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3681 buffer-undo-list))))
3683 (defun yas--snippet-create (begin end)
3684 "Creates a snippet from an template inserted between BEGIN and END.
3686 Returns the newly created snippet."
3687 (let ((snippet (yas--make-snippet)))
3689 (yas--snippet-parse-create snippet)
3691 ;; Sort and link each field
3692 (yas--snippet-sort-fields snippet)
3694 ;; Create keymap overlay for snippet
3695 (setf (yas--snippet-control-overlay snippet)
3696 (yas--make-control-overlay snippet (point-min) (point-max)))
3699 (goto-char (point-max))
3704 ;;; Apropos adjacencies and "fom's":
3706 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3707 ;; recently expanded snippet, we might actually have many fields,
3708 ;; mirrors (and the snippet exit) in the very same position in the
3709 ;; buffer. Therefore we need to single-link the
3710 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3711 ;; according to their original positions in the buffer.
3713 ;; Then we have operation `yas--advance-end-maybe' and
3714 ;; `yas--advance-start-maybe', which conditionally push the starts and
3715 ;; ends of these foms down the chain.
3717 ;; This allows for like the printf with the magic ",":
3719 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3720 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3722 (defun yas--fom-start (fom)
3723 (cond ((yas--field-p fom)
3724 (yas--field-start fom))
3725 ((yas--mirror-p fom)
3726 (yas--mirror-start fom))
3728 (yas--exit-marker fom))))
3730 (defun yas--fom-end (fom)
3731 (cond ((yas--field-p fom)
3732 (yas--field-end fom))
3733 ((yas--mirror-p fom)
3734 (yas--mirror-end fom))
3736 (yas--exit-marker fom))))
3738 (defun yas--fom-next (fom)
3739 (cond ((yas--field-p fom)
3740 (yas--field-next fom))
3741 ((yas--mirror-p fom)
3742 (yas--mirror-next fom))
3744 (yas--exit-next fom))))
3746 (defun yas--fom-parent-field (fom)
3747 (cond ((yas--field-p fom)
3748 (yas--field-parent-field fom))
3749 ((yas--mirror-p fom)
3750 (yas--mirror-parent-field fom))
3754 (defun yas--calculate-adjacencies (snippet)
3755 "Calculate adjacencies for fields or mirrors of SNIPPET.
3757 This is according to their relative positions in the buffer, and
3758 has to be called before the $-constructs are deleted."
3759 (labels ((yas--fom-set-next-fom (fom nextfom)
3760 (cond ((yas--field-p fom)
3761 (setf (yas--field-next fom) nextfom))
3762 ((yas--mirror-p fom)
3763 (setf (yas--mirror-next fom) nextfom))
3765 (setf (yas--exit-next fom) nextfom))))
3766 (yas--compare-fom-begs (fom1 fom2)
3767 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3768 (yas--mirror-p fom2)
3769 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3770 (yas--link-foms (fom1 fom2)
3771 (yas--fom-set-next-fom fom1 fom2)))
3772 ;; make some yas--field, yas--mirror and yas--exit soup
3774 (when (yas--snippet-exit snippet)
3775 (push (yas--snippet-exit snippet) soup))
3776 (dolist (field (yas--snippet-fields snippet))
3778 (dolist (mirror (yas--field-mirrors field))
3779 (push mirror soup)))
3782 #'yas--compare-fom-begs))
3784 (reduce #'yas--link-foms soup)))))
3786 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3787 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3789 Use the tightest containing field if more than one field contains
3790 the mirror. Intended to be called *before* the dollar-regions are
3792 (let ((min (point-min))
3794 (dolist (field (yas--snippet-fields snippet))
3795 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3796 (<= (yas--mirror-end mirror) (yas--field-end field))
3797 (< min (yas--field-start field))
3798 (< (yas--field-end field) max))
3799 (setq min (yas--field-start field)
3800 max (yas--field-end field))
3801 (setf (yas--mirror-parent-field mirror) field)))))
3803 (defun yas--advance-end-maybe (fom newend)
3804 "Maybe advance FOM's end to NEWEND if it needs it.
3808 * call `yas--advance-start-maybe' on FOM's next fom.
3810 * in case FOM is field call `yas--advance-end-maybe' on its parent
3813 Also, if FOM is an exit-marker, always call
3814 `yas--advance-start-maybe' on its next fom. This is because
3815 exit-marker have identical start and end markers."
3816 (cond ((and fom (< (yas--fom-end fom) newend))
3817 (set-marker (yas--fom-end fom) newend)
3818 (yas--advance-start-maybe (yas--fom-next fom) newend)
3819 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3821 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3823 (defun yas--advance-start-maybe (fom newstart)
3824 "Maybe advance FOM's start to NEWSTART if it needs it.
3826 If it does, also call `yas--advance-end-maybe' on FOM."
3827 (when (and fom (< (yas--fom-start fom) newstart))
3828 (set-marker (yas--fom-start fom) newstart)
3829 (yas--advance-end-maybe fom newstart)))
3831 (defun yas--advance-end-of-parents-maybe (field newend)
3832 "Like `yas--advance-end-maybe' but for parent fields.
3834 Only works for fields and doesn't care about the start of the
3835 next FOM. Works its way up recursively for parents of parents."
3837 (< (yas--field-end field) newend))
3838 (set-marker (yas--field-end field) newend)
3839 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3841 (defvar yas--dollar-regions nil
3842 "When expanding the snippet the \"parse-create\" functions add
3843 cons cells to this var.")
3845 (defvar yas--backquote-markers-and-strings nil
3846 "List of (MARKER . STRING) marking where the values from
3847 backquoted lisp expressions should be inserted at the end of
3850 (defun yas--snippet-parse-create (snippet)
3851 "Parse a recently inserted snippet template, creating all
3852 necessary fields, mirrors and exit points.
3854 Meant to be called in a narrowed buffer, does various passes"
3855 (let ((parse-start (point)))
3856 ;; Reset the yas--dollar-regions
3858 (setq yas--dollar-regions nil)
3859 ;; protect just the backquotes
3861 (yas--protect-escapes nil '(?`))
3862 ;; replace all backquoted expressions
3864 (goto-char parse-start)
3865 (yas--save-backquotes)
3866 ;; protect escaped characters
3868 (yas--protect-escapes)
3869 ;; parse fields with {}
3871 (goto-char parse-start)
3872 (yas--field-parse-create snippet)
3873 ;; parse simple mirrors and fields
3875 (goto-char parse-start)
3876 (yas--simple-mirror-parse-create snippet)
3877 ;; parse mirror transforms
3879 (goto-char parse-start)
3880 (yas--transform-mirror-parse-create snippet)
3881 ;; calculate adjacencies of fields and mirrors
3883 (yas--calculate-adjacencies snippet)
3884 ;; Delete $-constructs
3886 (yas--delete-regions yas--dollar-regions)
3887 ;; restore backquoted expression values
3889 (yas--restore-backquotes)
3892 (goto-char parse-start)
3893 (yas--restore-escapes)
3894 ;; update mirrors for the first time
3896 (yas--update-mirrors snippet)
3897 ;; indent the best we can
3899 (goto-char parse-start)
3900 (yas--indent snippet)))
3902 (defun yas--indent-according-to-mode (snippet-markers)
3903 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3904 ;;; Apropos indenting problems....
3906 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3907 ;; is available. Some implementations of these functions delete text
3908 ;; before they insert. If there happens to be a marker just after
3909 ;; the text being deleted, the insertion actually happens after the
3910 ;; marker, which misplaces it.
3912 ;; This would also happen if we had used overlays with the
3913 ;; `front-advance' property set to nil.
3915 ;; This is why I have these `trouble-markers', they are the ones at
3916 ;; they are the ones at the first non-whitespace char at the line
3917 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3918 ;; we should be at the correct to restore them to. All other
3919 ;; non-trouble-markers have been *pushed* and don't need special
3922 (goto-char (yas--real-line-beginning))
3923 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3929 (indent-according-to-mode)
3930 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3932 (mapc #'(lambda (marker)
3933 (set-marker marker (point)))
3936 (defvar yas--indent-original-column nil)
3937 (defun yas--indent (snippet)
3938 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3939 ;; Look for those $>
3941 (while (re-search-forward "$>" nil t)
3942 (delete-region (match-beginning 0) (match-end 0))
3943 (when (not (eq yas-indent-line 'auto))
3944 (yas--indent-according-to-mode snippet-markers))))
3945 ;; Now do stuff for 'fixed and 'auto
3947 (cond ((eq yas-indent-line 'fixed)
3948 (while (and (zerop (forward-line))
3949 (zerop (current-column)))
3950 (indent-to-column yas--indent-original-column)))
3951 ((eq yas-indent-line 'auto)
3952 (let ((end (set-marker (make-marker) (point-max)))
3953 (indent-first-line-p yas-also-auto-indent-first-line))
3954 (while (and (zerop (if indent-first-line-p
3957 (setq indent-first-line-p nil))
3961 (yas--indent-according-to-mode snippet-markers))))
3965 (defun yas--collect-snippet-markers (snippet)
3966 "Make a list of all the markers used by SNIPPET."
3968 (dolist (field (yas--snippet-fields snippet))
3969 (push (yas--field-start field) markers)
3970 (push (yas--field-end field) markers)
3971 (dolist (mirror (yas--field-mirrors field))
3972 (push (yas--mirror-start mirror) markers)
3973 (push (yas--mirror-end mirror) markers)))
3974 (let ((snippet-exit (yas--snippet-exit snippet)))
3975 (when (and snippet-exit
3976 (marker-buffer (yas--exit-marker snippet-exit)))
3977 (push (yas--exit-marker snippet-exit) markers)))
3980 (defun yas--real-line-beginning ()
3981 (let ((c (char-after (line-beginning-position)))
3982 (n (line-beginning-position)))
3983 (while (or (eql c ?\ )
3986 (setq c (char-after n)))
3989 (defun yas--escape-string (escaped)
3990 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3992 (defun yas--protect-escapes (&optional text escaped)
3993 "Protect all escaped characters with their numeric ASCII value.
3995 With optional string TEXT do it in string instead of buffer."
3996 (let ((changed-text text)
3997 (text-provided-p text))
3998 (mapc #'(lambda (escaped)
4000 (yas--replace-all (concat "\\" (char-to-string escaped))
4001 (yas--escape-string escaped)
4002 (when text-provided-p changed-text))))
4003 (or escaped yas--escaped-characters))
4006 (defun yas--restore-escapes (&optional text escaped)
4007 "Restore all escaped characters from their numeric ASCII value.
4009 With optional string TEXT do it in string instead of the buffer."
4010 (let ((changed-text text)
4011 (text-provided-p text))
4012 (mapc #'(lambda (escaped)
4014 (yas--replace-all (yas--escape-string escaped)
4015 (char-to-string escaped)
4016 (when text-provided-p changed-text))))
4017 (or escaped yas--escaped-characters))
4020 (defun yas--save-backquotes ()
4021 "Save all the \"`(lisp-expression)`\"-style expressions
4022 with their evaluated value into `yas--backquote-markers-and-strings'."
4023 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4024 (let ((current-string (match-string-no-properties 1)) transformed)
4025 (delete-region (match-beginning 0) (match-end 0))
4026 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4027 (goto-char (match-beginning 0))
4029 (let ((marker (make-marker)))
4030 (insert "Y") ;; quite horrendous, I love it :)
4031 (set-marker marker (point))
4033 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4035 (defun yas--restore-backquotes ()
4036 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4037 (while yas--backquote-markers-and-strings
4038 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4039 (marker (car marker-and-string))
4040 (string (cdr marker-and-string)))
4046 (set-marker marker nil)))))
4048 (defun yas--scan-sexps (from count)
4050 (with-syntax-table (standard-syntax-table)
4051 (scan-sexps from count))
4055 (defun yas--make-marker (pos)
4056 "Create a marker at POS with nil `marker-insertion-type'."
4057 (let ((marker (set-marker (make-marker) pos)))
4058 (set-marker-insertion-type marker nil)
4061 (defun yas--field-parse-create (snippet &optional parent-field)
4062 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4064 The following count as a field:
4066 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4068 * \"${n: text$(expression)}, the same with a lisp expression;
4069 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4071 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4073 When multiple expressions are found, only the last one counts."
4076 (while (re-search-forward yas--field-regexp nil t)
4077 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4078 (number (and (match-string-no-properties 1)
4079 (string-to-number (match-string-no-properties 1))))
4080 (brand-new-field (and real-match-end-0
4081 ;; break if on "$(" immediately
4082 ;; after the ":", this will be
4083 ;; caught as a mirror with
4085 (not (save-match-data
4086 (eq (string-match "$[ \t\n]*("
4087 (match-string-no-properties 2)) 0)))
4088 ;; allow ${0: some exit text}
4089 ;; (not (and number (zerop number)))
4090 (yas--make-field number
4091 (yas--make-marker (match-beginning 2))
4092 (yas--make-marker (1- real-match-end-0))
4094 (when brand-new-field
4095 (goto-char real-match-end-0)
4096 (push (cons (1- real-match-end-0) real-match-end-0)
4097 yas--dollar-regions)
4098 (push (cons (match-beginning 0) (match-beginning 2))
4099 yas--dollar-regions)
4100 (push brand-new-field (yas--snippet-fields snippet))
4103 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4104 (goto-char (point-min))
4105 (yas--field-parse-create snippet brand-new-field)))))))
4106 ;; if we entered from a parent field, now search for the
4107 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4108 ;; primary field transformations
4112 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4113 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4114 ;; commit the primary field transformation if:
4116 ;; 1. we don't find it in yas--dollar-regions (a subnested
4117 ;; field) might have already caught it.
4119 ;; 2. we really make sure we have either two '$' or some
4120 ;; text and a '$' after the colon ':'. This is a FIXME: work
4121 ;; my regular expressions and end these ugly hacks.
4123 (when (and real-match-end-1
4124 (not (member (cons (match-beginning 0)
4126 yas--dollar-regions))
4128 (char-before (1- (match-beginning 1))))))
4129 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4131 (setf (yas--field-transform parent-field)
4132 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4133 (push (cons (match-beginning 0) real-match-end-1)
4134 yas--dollar-regions)))))))
4136 (defun yas--transform-mirror-parse-create (snippet)
4137 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4138 (while (re-search-forward yas--transform-mirror-regexp nil t)
4139 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4140 (number (string-to-number (match-string-no-properties 1)))
4142 (not (zerop number))
4143 (yas--snippet-find-field snippet number)))
4145 (and real-match-end-0
4147 (yas--make-mirror (yas--make-marker (match-beginning 0))
4148 (yas--make-marker (match-beginning 0))
4150 (yas--restore-escapes
4151 (buffer-substring-no-properties (match-beginning 2)
4152 (1- real-match-end-0))))))))
4153 (when brand-new-mirror
4154 (push brand-new-mirror
4155 (yas--field-mirrors field))
4156 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4157 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4159 (defun yas--simple-mirror-parse-create (snippet)
4160 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4161 (while (re-search-forward yas--simple-mirror-regexp nil t)
4162 (let ((number (string-to-number (match-string-no-properties 1))))
4163 (cond ((zerop number)
4165 (setf (yas--snippet-exit snippet)
4166 (yas--make-exit (yas--make-marker (match-end 0))))
4168 (goto-char (match-beginning 0))
4169 (when yas-wrap-around-region
4170 (cond (yas-selected-text
4171 (insert yas-selected-text))
4172 ((and (eq yas-wrap-around-region 'cua)
4175 (insert (prog1 (get-register ?0)
4176 (set-register ?0 nil))))))
4177 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4178 yas--dollar-regions)))
4180 (let ((field (yas--snippet-find-field snippet number)))
4182 (let ((brand-new-mirror (yas--make-mirror
4183 (yas--make-marker (match-beginning 0))
4184 (yas--make-marker (match-beginning 0))
4186 (push brand-new-mirror
4187 (yas--field-mirrors field))
4188 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4189 (push (yas--make-field number
4190 (yas--make-marker (match-beginning 0))
4191 (yas--make-marker (match-beginning 0))
4193 (yas--snippet-fields snippet))))
4194 (push (cons (match-beginning 0) (match-end 0))
4195 yas--dollar-regions))))))
4197 (defun yas--delete-regions (regions)
4198 "Sort disjuct REGIONS by start point, then delete from the back."
4199 (mapc #'(lambda (reg)
4200 (delete-region (car reg) (cdr reg)))
4203 (>= (car r1) (car r2))))))
4205 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4206 (let* ((parent (yas--mirror-parent-field mirror))
4207 (parents-mirrors (and parent
4208 (yas--field-mirrors parent))))
4209 (or (yas--mirror-depth mirror)
4210 (setf (yas--mirror-depth mirror)
4211 (cond ((memq mirror traversed)
4213 ((and parent parents-mirrors)
4215 (mapcar #'(lambda (m)
4216 (yas--calculate-mirror-depth m
4225 (defun yas--update-mirrors (snippet)
4226 "Updates all the mirrors of SNIPPET."
4228 (dolist (field-and-mirror (sort
4229 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4230 ;; where F is the field that M is mirroring
4232 (mapcan #'(lambda (field)
4233 (mapcar #'(lambda (mirror)
4234 (cons field mirror))
4235 (yas--field-mirrors field)))
4236 (yas--snippet-fields snippet))
4237 ;; then sort this list so that entries with mirrors with parent
4238 ;; fields appear before. This was important for fixing #290, and
4239 ;; luckily also handles the case where a mirror in a field causes
4240 ;; another mirror to need reupdating
4242 #'(lambda (field-and-mirror1 field-and-mirror2)
4243 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4244 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4245 (let* ((field (car field-and-mirror))
4246 (mirror (cdr field-and-mirror))
4247 (parent-field (yas--mirror-parent-field mirror)))
4248 ;; before updating a mirror with a parent-field, maybe advance
4252 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4253 ;; update this mirror
4255 (yas--mirror-update-display mirror field)
4256 ;; `yas--place-overlays' is needed if the active field and
4257 ;; protected overlays have been changed because of insertions
4258 ;; in `yas--mirror-update-display'
4260 (when (eq field (yas--snippet-active-field snippet))
4261 (yas--place-overlays snippet field))))))
4263 (defun yas--mirror-update-display (mirror field)
4264 "Update MIRROR according to FIELD (and mirror transform)."
4266 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4267 (reflection (and (not (and mirror-parent-field
4268 (yas--field-modified-p mirror-parent-field)))
4269 (or (yas--apply-transform mirror field 'empty-on-nil)
4270 (yas--field-text-for-display field)))))
4271 (when (and reflection
4272 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4273 (yas--mirror-end mirror)))))
4274 (goto-char (yas--mirror-start mirror))
4275 (yas--inhibit-overlay-hooks
4276 (insert reflection))
4277 (if (> (yas--mirror-end mirror) (point))
4278 (delete-region (point) (yas--mirror-end mirror))
4279 (set-marker (yas--mirror-end mirror) (point))
4280 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4281 ;; super-special advance
4282 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4284 (defun yas--field-update-display (field snippet)
4285 "Much like `yas--mirror-update-display', but for fields."
4286 (when (yas--field-transform field)
4287 (let ((transformed (and (not (eq (yas--field-number field) 0))
4288 (yas--apply-transform field field)))
4290 (when (and transformed
4291 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4292 (yas--field-end field)))))
4293 (setf (yas--field-modified-p field) t)
4294 (goto-char (yas--field-start field))
4295 (yas--inhibit-overlay-hooks
4296 (insert transformed)
4297 (if (> (yas--field-end field) (point))
4298 (delete-region (point) (yas--field-end field))
4299 (set-marker (yas--field-end field) (point))
4300 (yas--advance-start-maybe (yas--field-next field) (point)))
4304 ;;; Post-command hook:
4306 (defun yas--post-command-handler ()
4307 "Handles various yasnippet conditions after each command."
4308 (cond (yas--protection-violation
4309 (goto-char yas--protection-violation)
4310 (setq yas--protection-violation nil))
4311 ((eq 'undo this-command)
4313 ;; After undo revival the correct field is sometimes not
4314 ;; restored correctly, this condition handles that
4316 (let* ((snippet (car (yas--snippets-at-point)))
4317 (target-field (and snippet
4318 (find-if-not #'(lambda (field)
4319 (yas--field-probably-deleted-p snippet field))
4321 (cons (yas--snippet-active-field snippet)
4322 (yas--snippet-fields snippet)))))))
4324 (yas--move-to-field snippet target-field))))
4325 ((not (yas--undo-in-progress))
4326 ;; When not in an undo, check if we must commit the snippet
4327 ;; (user exited it).
4328 (yas--check-commit-snippet))))
4332 ;; The docstrings for some functions are generated dynamically
4333 ;; depending on the context.
4335 (put 'yas-expand 'function-documentation
4336 '(yas--expand-from-trigger-key-doc))
4337 (defun yas--expand-from-trigger-key-doc ()
4338 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4339 (let ((fallback-description
4340 (cond ((eq yas-fallback-behavior 'call-other-command)
4341 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4343 (format " call command `%s'." (pp-to-string fallback)))
4344 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4345 ((eq yas-fallback-behavior 'return-nil)
4348 ", defer to `yas-fallback-behaviour' (which see)"))))
4349 (concat "Expand a snippet before point. If no snippet
4350 expansion is possible,"
4351 fallback-description
4352 "\n\nOptional argument FIELD is for non-interactive use and is an
4353 object satisfying `yas--field-p' to restrict the expansion to.")))
4355 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4356 (defun yas--expand-from-keymap-doc ()
4357 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4358 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4359 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4360 (when (eq this-command 'describe-key)
4361 (let* ((vec (this-single-command-keys))
4362 (templates (mapcan #'(lambda (table)
4363 (yas--fetch table vec))
4364 (yas--get-snippet-tables)))
4365 (yas--direct-keymaps nil)
4366 (fallback (key-binding vec)))
4367 (concat "In this case, "
4369 (concat "these snippets are bound to this key:\n"
4370 (yas--template-pretty-list templates)
4371 "\n\nIf none of these expands, "))
4373 (format "fallback `%s' will be called." (pp-to-string fallback)))
4374 "no fallback keybinding is called."))))))
4376 (defun yas--template-pretty-list (templates)
4378 (yas-buffer-local-condition 'always))
4379 (dolist (plate templates)
4380 (setq acc (concat acc "\n*) "
4381 (propertize (concat "\\\\snippet `" (car plate) "'")
4382 'yasnippet (cdr plate)))))
4385 (define-button-type 'help-snippet-def
4386 :supertype 'help-xref
4387 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4388 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4390 (defun yas--snippet-description-finish-runonce ()
4391 "Final adjustments for the help buffer when snippets are concerned."
4392 (yas--create-snippet-xrefs)
4393 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4395 (defun yas--create-snippet-xrefs ()
4397 (goto-char (point-min))
4398 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4399 (let ((template (get-text-property (match-beginning 1)
4402 (help-xref-button 1 'help-snippet-def template)
4403 (kill-region (match-end 1) (match-end 0))
4404 (kill-region (match-beginning 0) (match-beginning 1)))))))
4406 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4407 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4409 Remaining args as in `yas-expand-snippet'."
4410 (let* ((table (gethash mode-symbol yas--tables))
4411 (yas--current-template (and table
4412 (gethash uuid (yas--table-uuidhash table)))))
4413 (when yas--current-template
4414 (yas-expand-snippet (yas--template-content yas--current-template)))))
4418 (defvar yas-verbosity 4
4419 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4421 (defun yas--message (level message &rest args)
4422 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4423 (when (> yas-verbosity level)
4424 (message "%s" (apply #'yas--format message args))))
4426 (defun yas--format (format-control &rest format-args)
4427 (apply #'format (concat "[yas] " format-control) format-args))
4434 ;; `locate-dominating-file'
4435 ;; `region-active-p'
4437 ;; added for compatibility in emacsen < 23
4438 (unless (>= emacs-major-version 23)
4439 (unless (fboundp 'region-active-p)
4440 (defun region-active-p () (and transient-mark-mode mark-active)))
4442 (unless (fboundp 'locate-dominating-file)
4443 (defvar locate-dominating-stop-dir-regexp
4444 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4445 "Regexp of directory names which stop the search in `locate-dominating-file'.
4446 Any directory whose name matches this regexp will be treated like
4447 a kind of root directory by `locate-dominating-file' which will stop its search
4448 when it bumps into it.
4449 The default regexp prevents fruitless and time-consuming attempts to find
4450 special files in directories in which filenames are interpreted as hostnames,
4451 or mount points potentially requiring authentication as a different user.")
4453 (defun locate-dominating-file (file name)
4454 "Look up the directory hierarchy from FILE for a file named NAME.
4455 Stop at the first parent directory containing a file NAME,
4456 and return the directory. Return nil if not found."
4457 ;; We used to use the above locate-dominating-files code, but the
4458 ;; directory-files call is very costly, so we're much better off doing
4459 ;; multiple calls using the code in here.
4461 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4462 ;; `name' in /home or in /.
4463 (setq file (abbreviate-file-name file))
4466 ;; `user' is not initialized outside the loop because
4467 ;; `file' may not exist, so we may have to walk up part of the
4468 ;; hierarchy before we find the "initial UUID".
4471 (while (not (or root
4473 ;; FIXME: Disabled this heuristic because it is sometimes
4475 ;; As a heuristic, we stop looking up the hierarchy of
4476 ;; directories as soon as we find a directory belonging
4477 ;; to another user. This should save us from looking in
4478 ;; things like /net and /afs. This assumes that all the
4479 ;; files inside a project belong to the same user.
4480 ;; (let ((prev-user user))
4481 ;; (setq user (nth 2 (file-attributes file)))
4482 ;; (and prev-user (not (equal user prev-user))))
4483 (string-match locate-dominating-stop-dir-regexp file)))
4484 (setq try (file-exists-p (expand-file-name name file)))
4485 (cond (try (setq root file))
4486 ((equal file (setq prev-file file
4487 file (file-name-directory
4488 (directory-file-name file))))
4492 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4493 ;; (when it execute forward-char) and interrupt the after change
4494 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4495 ;; invoked. Here's a way to reproduce it:
4497 ;; # open a *new* Emacs.
4498 ;; # load yasnippet.
4499 ;; # open a *new* .cpp file.
4500 ;; # input "inc" and press TAB to expand the snippet.
4501 ;; # select the `#include <...>` snippet.
4502 ;; # type inside `<>`
4504 (defadvice c-neutralize-syntax-in-CPP
4505 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4506 "Adviced `c-neutralize-syntax-in-CPP' to properly
4507 handle the end-of-buffer error fired in it by calling
4508 `forward-char' at the end of buffer."
4511 (error (message (error-message-string err)))))
4513 ;; disable c-electric-* serial command in YAS fields
4514 (add-hook 'c-mode-common-hook
4516 (dolist (k '(":" ">" ";" "<" "{" "}"))
4517 (define-key (symbol-value (make-local-variable 'yas-keymap))
4518 k 'self-insert-command))))
4520 ;;; Backward compatibility to yasnippet <= 0.7
4522 (defvar yas--exported-syms '(;; `defcustom's
4525 yas-prompt-functions
4527 yas-also-auto-indent-first-line
4529 yas-triggers-in-field
4530 yas-fallback-behavior
4531 yas-choose-keys-first
4532 yas-choose-tables-first
4535 yas-wrap-around-region
4538 yas-expand-only-for-last-commands
4539 yas-field-highlight-face
4541 ;; these vars can be customized as well
4547 yas-after-exit-snippet-hook
4548 yas-before-expand-snippet-hook
4549 yas-buffer-local-condition
4552 ;; prompting functions
4557 yas-completing-prompt
4560 ;; interactive functions
4565 yas-direct-keymaps-reload
4569 yas-compile-directory
4572 yas-expand-from-trigger-key
4573 yas-expand-from-keymap
4575 yas-visit-snippet-file
4577 yas-load-snippet-buffer
4580 yas-next-field-or-maybe-expand
4585 yas-exit-all-snippets
4586 yas-skip-and-clear-or-delete-char
4588 ;; symbols that I "exported" for use
4589 ;; in snippets and hookage
4607 yas-default-from-field
4610 yas-define-condition-cache
4611 yas-hippie-try-expand
4614 ;; debug definitions
4615 ;; yas-debug-snippet-vars
4616 ;; yas-exterminate-package
4619 ;; testing definitions
4620 ;; yas-should-expand
4621 ;; yas-should-not-expand
4623 ;; yas-make-file-or-dirs
4625 ;; yas-saving-variables
4626 ;; yas-call-with-snippet-dirs
4627 ;; yas-with-snippet-dirs
4629 "Exported yasnippet symbols.
4631 i.e. ones that I will try to keep in future yasnippet versions
4632 and ones that other elisp libraries can more or less safely rely
4635 (defvar yas--dont-backport '(yas-active-keys)
4636 "Exported symbols that don't map back to \"yas/*\" variants.")
4638 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4639 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4641 (make-obsolete-variable backported sym "yasnippet 0.8")
4642 (defvaralias backported sym))
4644 (make-obsolete backported sym "yasnippet 0.8")
4645 (defalias backported sym))))
4648 (provide 'yasnippet)
4650 ;;; yasnippet.el ends here
4653 ;; byte-compile-warnings: (not cl-functions)