1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
5 ;; Maintainer: João Távora <joaotavora@gmail.com>
7 ;; Package-version: 0.8.0
8 ;; X-URL: http://github.com/capitaomorte/yasnippet
9 ;; Keywords: convenience, emulation
10 ;; URL: http://github.com/capitaomorte/yasnippet
11 ;; EmacsWiki: YaSnippetMode
13 ;; This program is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Basic steps to setup:
30 ;; (add-to-list 'load-path
31 ;; "~/path-to-yasnippet")
32 ;; (require 'yasnippet)
33 ;; (yas-global-mode 1)
36 ;; Interesting variables are:
40 ;; The directory where user-created snippets are to be
41 ;; stored. Can also be a list of directories. In that case,
42 ;; when used for bulk (re)loading of snippets (at startup or
43 ;; via `yas-reload-all'), directories appearing earlier in
44 ;; the list shadow other dir's snippets. Also, the first
45 ;; directory is taken as the default for storing the user's
48 ;; The deprecated `yas/root-directory' aliases this variable
49 ;; for backward-compatibility.
53 ;; A local variable that you can set in a hook to override
54 ;; snippet-lookup based on major mode. It is a symbol (or
55 ;; list of symbols) that correspond to subdirectories of
56 ;; `yas-snippet-dirs' and is used for deciding which
57 ;; snippets to consider for the active buffer.
59 ;; Deprecated `yas/mode-symbol' aliases this variable for
60 ;; backward-compatibility.
62 ;; Major commands are:
66 ;; Try to expand snippets before point. In `yas-minor-mode',
67 ;; this is normally bound to TAB, but you can customize it in
68 ;; `yas-minor-mode-map'.
70 ;; M-x yas-load-directory
72 ;; Prompts you for a directory hierarchy of snippets to load.
74 ;; M-x yas-insert-snippet
76 ;; Prompts you for possible snippet expansion if that is
77 ;; possible according to buffer-local and snippet-local
78 ;; expansion conditions. With prefix argument, ignore these
81 ;; M-x yas-visit-snippet-file
83 ;; Prompts you for possible snippet expansions like
84 ;; `yas-insert-snippet', but instead of expanding it, takes
85 ;; you directly to the snippet definition's file, if it
88 ;; M-x yas-new-snippet
90 ;; Lets you create a new snippet file in the correct
91 ;; subdirectory of `yas-snippet-dirs', according to the
94 ;; M-x yas-load-snippet-buffer
96 ;; When editing a snippet, this loads the snippet. This is
97 ;; bound to "C-c C-c" while in the `snippet-mode' editing
100 ;; M-x yas-tryout-snippet
102 ;; When editing a snippet, this opens a new empty buffer,
103 ;; sets it to the appropriate major mode and inserts the
104 ;; snippet there, so you can see what it looks like. This is
105 ;; bound to "C-c C-t" while in `snippet-mode'.
107 ;; M-x yas-describe-tables
109 ;; Lists known snippets in a separate buffer. User is
110 ;; prompted as to whether only the currently active tables
111 ;; are to be displayed, or all the tables for all major
114 ;; If you have `dropdown-list' installed, you can optionally use it
115 ;; as the preferred "prompting method", putting in your .emacs file,
118 ;; (require 'dropdown-list)
119 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
121 ;; yas-completing-prompt))
123 ;; Also check out the customization group
125 ;; M-x customize-group RET yasnippet RET
127 ;; If you use the customization group to set variables
128 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
129 ;; "yasnippet.el" is present in the `load-path' *before* the
130 ;; `custom-set-variables' is executed in your .emacs file.
132 ;; For more information and detailed usage, refer to the project page:
133 ;; 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)
148 (defvar yas--current-template)
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 "Return `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.
200 If nil, don't use any snippet."
204 (defcustom yas-prompt-functions '(yas-x-prompt
206 yas-completing-prompt
209 "Functions to prompt for keys, templates, etc interactively.
211 These functions are called with the following arguments:
213 - PROMPT: A string to prompt the user
215 - CHOICES: a list of strings or objects.
217 - optional DISPLAY-FN : A function that, when applied to each of
218 the objects in CHOICES will return a string.
220 The return value of any function you put here should be one of
221 the objects in CHOICES, properly formatted with DISPLAY-FN (if
224 - To signal that your particular style of prompting is
225 unavailable at the moment, you can also have the function return
228 - To signal that the user quit the prompting process, you can
231 (signal 'quit \"user quit!\")."
232 :type '(repeat function)
235 (defcustom yas-indent-line 'auto
236 "Controls indenting applied to a recent snippet expansion.
238 The following values are possible:
240 - `fixed' Indent the snippet to the current column;
242 - `auto' Indent each line of the snippet with `indent-according-to-mode'
244 Every other value means don't apply any snippet-side indentation
245 after expansion (the manual per-line \"$>\" indentation still
247 :type '(choice (const :tag "Nothing" nothing)
248 (const :tag "Fixed" fixed)
249 (const :tag "Auto" auto))
252 (defcustom yas-also-auto-indent-first-line nil
253 "Non-nil means also auto indent first line according to mode.
255 Naturally this is only valid when `yas-indent-line' is `auto'"
259 (defcustom yas-snippet-revival t
260 "Non-nil means re-activate snippet fields after undo/redo."
264 (defcustom yas-triggers-in-field nil
265 "If non-nil, allow stacked expansions (snippets inside snippets).
267 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
272 (defcustom yas-fallback-behavior 'call-other-command
273 "How to act when `yas-expand' does *not* expand a snippet.
275 - `call-other-command' means try to temporarily disable YASnippet
276 and call the next command bound to whatever key was used to
279 - nil or the symbol `return-nil' mean do nothing. (and
280 `yas-expand' returns nil)
282 - A Lisp form (apply COMMAND . ARGS) means interactively call
283 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
284 with ARGS as arguments."
285 :type '(choice (const :tag "Call previous command" call-other-command)
286 (const :tag "Do nothing" return-nil))
289 (defcustom yas-choose-keys-first nil
290 "If non-nil, prompt for snippet key first, then for template.
292 Otherwise prompts for all possible snippet names.
294 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
298 (defcustom yas-choose-tables-first nil
299 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
301 Otherwise, user chooses between the merging together of all
304 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
308 (defcustom yas-use-menu 'abbreviate
309 "Display a YASnippet menu in the menu bar.
311 When non-nil, submenus for each snippet table will be listed
312 under the menu \"Yasnippet\".
314 - If set to `abbreviate', only the current major-mode
315 menu and the modes set in `yas-extra-modes' are listed.
317 - If set to `full', every submenu is listed
319 - It set to nil, don't display a menu at all (this requires a
320 `yas-reload-all' call if the menu is already visible).
322 Any other non-nil value, every submenu is listed."
323 :type '(choice (const :tag "Full" full)
324 (const :tag "Abbreviate" abbreviate)
325 (const :tag "No menu" nil))
328 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
330 (char-to-string ?\x21E5))) ;; little ->| sign
332 "The text that will be used in menu to represent the trigger."
336 (defcustom yas-wrap-around-region nil
337 "If non-nil, snippet expansion wraps around selected region.
339 The wrapping occurs just before the snippet's exit marker. This
340 can be overridden on a per-snippet basis."
344 (defcustom yas-good-grace t
345 "If non-nil, don't raise errors in inline elisp evaluation.
347 An error string \"[yas] error\" is returned instead."
351 (defcustom yas-visit-from-menu nil
352 "If non-nil visit snippets's files from menu, instead of expanding them.
354 This can only work when snippets are loaded from files."
358 (defcustom yas-expand-only-for-last-commands nil
359 "List of `last-command' values to restrict tab-triggering to, or nil.
361 Leave this set at nil (the default) to be able to trigger an
362 expansion simply by placing the cursor after a valid tab trigger,
363 using whichever commands.
365 Optionally, set this to something like '(self-insert-command) if
366 you to wish restrict expansion to only happen when the last
367 letter of the snippet tab trigger was typed immediately before
368 the trigger key itself."
369 :type '(repeat function)
372 ;; Only two faces, and one of them shouldn't even be used...
374 (defface yas-field-highlight-face
375 '((t (:inherit 'region)))
376 "The face used to highlight the currently active field of a snippet"
379 (defface yas--field-debug-face
381 "The face used for debugging some overlays normally hidden"
385 ;;; User-visible variables
387 (defvar yas-keymap (let ((map (make-sparse-keymap)))
388 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
389 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
390 (define-key map [(shift tab)] 'yas-prev-field)
391 (define-key map [backtab] 'yas-prev-field)
392 (define-key map (kbd "C-g") 'yas-abort-snippet)
393 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
395 "The active keymap while a snippet expansion is in progress.")
397 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
398 "List of character syntaxes used to find a trigger key before point.
399 The list is tried in the order while scanning characters
400 backwards from point. For example, if the list is '(\"w\" \"w_\")
401 first look for trigger keys which are composed exclusively of
402 \"word\"-syntax characters, and then, if that fails, look for
403 keys which are either of \"word\" or \"symbol\"
404 syntax. Triggering after
408 will, according to the \"w\" element first try \"bar\". If that
409 isn't a trigger key, \"foo-bar\" is tried, respecting a second
412 (defvar yas-after-exit-snippet-hook
414 "Hooks to run after a snippet exited.
416 The hooks will be run in an environment where some variables bound to
419 `yas-snippet-beg' : The beginning of the region of the snippet.
421 `yas-snippet-end' : Similar to beg.
423 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
425 (defvar yas-before-expand-snippet-hook
427 "Hooks to run just before expanding a snippet.")
429 (defvar yas-buffer-local-condition
430 '(if (and (or (fourth (syntax-ppss))
431 (fifth (syntax-ppss)))
433 (eq this-command 'yas-expand-from-trigger-key))
434 '(require-snippet-condition . force-in-comment)
436 "Snippet expanding condition.
438 This variable is a Lisp form which is evaluated every time a
439 snippet expansion is attempted:
441 * If it evaluates to nil, no snippets can be expanded.
443 * If it evaluates to the a cons (require-snippet-condition
446 * Snippets bearing no \"# condition:\" directive are not
449 * Snippets bearing conditions that evaluate to nil (or
450 produce an error) won't be considered.
452 * If the snippet has a condition that evaluates to non-nil
455 * If REQUIREMENT is t, the snippet is considered
457 * If REQUIREMENT is `eq' RESULT, the snippet is
460 * Otherwise, the snippet is not considered.
462 * If it evaluates to the symbol 'always, all snippets are
463 considered for expansion, regardless of any conditions.
465 * If it evaluates to t or some other non-nil value
467 * Snippet bearing no conditions, or conditions that
468 evaluate to non-nil, are considered for expansion.
470 * Otherwise, the snippet is not considered.
472 Here's an example preventing snippets from being expanded from
473 inside comments, in `python-mode' only, with the exception of
474 snippets returning the symbol 'force-in-comment in their
477 (add-hook 'python-mode-hook
479 (setq yas-buffer-local-condition
480 '(if (python-in-string/comment)
481 '(require-snippet-condition . force-in-comment)
484 The default value is similar, it filters out potential snippet
485 expansions inside comments and string literals, unless the
486 snippet itself contains a condition that returns the symbol
487 `force-in-comment'.")
490 ;;; Internal variables
492 (defvar yas--version "0.8.0beta")
494 (defvar yas--menu-table (make-hash-table)
495 "A hash table of MAJOR-MODE symbols to menu keymaps.")
497 (defvar yas--known-modes
498 '(ruby-mode rst-mode markdown-mode)
499 "A list of mode which is well known but not part of Emacs.")
501 (defvar yas--escaped-characters
502 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
503 "List of characters which *might* need to be escaped.")
505 (defconst yas--field-regexp
506 "${\\([0-9]+:\\)?\\([^}]*\\)}"
507 "A regexp to *almost* recognize a field.")
509 (defconst yas--multi-dollar-lisp-expression-regexp
510 "$+[ \t\n]*\\(([^)]*)\\)"
511 "A regexp to *almost* recognize a \"$(...)\" expression.")
513 (defconst yas--backquote-lisp-expression-regexp
515 "A regexp to recognize a \"`lisp-expression`\" expression." )
517 (defconst yas--transform-mirror-regexp
518 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
519 "A regexp to *almost* recognize a mirror with a transform.")
521 (defconst yas--simple-mirror-regexp
523 "A regexp to recognize a simple mirror.")
525 (defvar yas--snippet-id-seed 0
526 "Contains the next id for a snippet.")
528 (defun yas--snippet-next-id ()
529 (let ((id yas--snippet-id-seed))
530 (incf yas--snippet-id-seed)
536 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
537 (defvar last-buffer-undo-list nil)
539 (defvar yas--minor-mode-menu nil
540 "Holds the YASnippet menu.")
542 (defun yas--init-minor-keymap ()
543 "Set up the `yas-minor-mode' keymap."
544 (let ((map (make-sparse-keymap)))
546 (easy-menu-define yas--minor-mode-menu
548 "Menu used when `yas-minor-mode' is active."
551 ["Expand trigger" yas-expand
552 :help "Possibly expand tab trigger before point"]
553 ["Insert at point..." yas-insert-snippet
554 :help "Prompt for an expandable snippet and expand it at point"]
555 ["New snippet..." yas-new-snippet
556 :help "Create a new snippet in an appropriate directory"]
557 ["Visit snippet file..." yas-visit-snippet-file
558 :help "Prompt for an expandable snippet and find its file"]
560 ("Snippet menu behaviour"
561 ["Visit snippets" (setq yas-visit-from-menu t)
562 :help "Visit snippets from the menu"
563 :active t :style radio :selected yas-visit-from-menu]
564 ["Expand snippets" (setq yas-visit-from-menu nil)
565 :help "Expand snippets from the menu"
566 :active t :style radio :selected (not yas-visit-from-menu)]
568 ["Show all known modes" (setq yas-use-menu 'full)
569 :help "Show one snippet submenu for each loaded table"
570 :active t :style radio :selected (eq yas-use-menu 'full)]
571 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
572 :help "Show only snippet submenus for the current active modes"
573 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
575 ["Auto" (setq yas-indent-line 'auto)
576 :help "Indent each line of the snippet with `indent-according-to-mode'"
577 :active t :style radio :selected (eq yas-indent-line 'auto)]
578 ["Fixed" (setq yas-indent-line 'fixed)
579 :help "Indent the snippet to the current column"
580 :active t :style radio :selected (eq yas-indent-line 'fixed)]
581 ["None" (setq yas-indent-line 'none)
582 :help "Don't apply any particular snippet indentation after expansion"
583 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
585 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
586 (not yas-also-auto-indent-first-line))
587 :help "When auto-indenting also, auto indent the first line menu"
588 :active (eq yas-indent-line 'auto)
589 :style toggle :selected yas-also-auto-indent-first-line]
592 ["System X-widget" (setq yas-prompt-functions
594 (remove 'yas-x-prompt
595 yas-prompt-functions)))
596 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
597 :active t :style radio :selected (eq (car yas-prompt-functions)
599 ["Dropdown-list" (setq yas-prompt-functions
600 (cons 'yas-dropdown-prompt
601 (remove 'yas-dropdown-prompt
602 yas-prompt-functions)))
603 :help "Use a special dropdown list"
604 :active t :style radio :selected (eq (car yas-prompt-functions)
605 'yas-dropdown-prompt)]
606 ["Ido" (setq yas-prompt-functions
607 (cons 'yas-ido-prompt
608 (remove 'yas-ido-prompt
609 yas-prompt-functions)))
610 :help "Use an ido-style minibuffer prompt"
611 :active t :style radio :selected (eq (car yas-prompt-functions)
613 ["Completing read" (setq yas-prompt-functions
614 (cons 'yas-completing-prompt
615 (remove 'yas-completing-prompt
616 yas-prompt-functions)))
617 :help "Use a normal minibuffer prompt"
618 :active t :style radio :selected (eq (car yas-prompt-functions)
619 'yas-completing-prompt)]
622 ["Wrap region in exit marker"
623 (setq yas-wrap-around-region
624 (not yas-wrap-around-region))
625 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
626 :style toggle :selected yas-wrap-around-region]
627 ["Allow stacked expansions "
628 (setq yas-triggers-in-field
629 (not yas-triggers-in-field))
630 :help "If non-nil allow snippets to be triggered inside other snippet fields"
631 :style toggle :selected yas-triggers-in-field]
632 ["Revive snippets on undo "
633 (setq yas-snippet-revival
634 (not yas-snippet-revival))
635 :help "If non-nil allow snippets to become active again after undo"
636 :style toggle :selected yas-snippet-revival]
639 (not yas-good-grace))
640 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
641 :style toggle :selected yas-good-grace]
644 ["Load snippets..." yas-load-directory
645 :help "Load snippets from a specific directory"]
646 ["Reload everything" yas-reload-all
647 :help "Cleanup stuff, reload snippets, rebuild menus"]
649 :help "Display some information about YASnippet"])))
651 ;; Now for the stuff that has direct keybindings
653 (define-key map [(tab)] 'yas-expand)
654 (define-key map (kbd "TAB") 'yas-expand)
655 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
656 (define-key map "\C-c&\C-n" 'yas-new-snippet)
657 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
660 (defvar yas-minor-mode-map (yas--init-minor-keymap)
661 "The keymap used when `yas-minor-mode' is active.")
663 (defvar yas--tables (make-hash-table)
664 "A hash table of mode symbols to `yas--table' objects.")
666 (defvar yas--parents (make-hash-table)
667 "A hash table of mode symbols do lists of direct parent mode symbols.
669 This list is populated when reading the \".yas-parents\" files
670 found when traversing snippet directories with
671 `yas-load-directory'.
673 There might be additional parenting information stored in the
674 `derived-mode-parent' property of some mode symbols, but that is
677 (defvar yas--ancestors (make-hash-table)
678 "A hash table of mode symbols do lists of all parent mode symbols.
680 A cache managed by `yas--all-parents'")
682 (defvar yas--direct-keymaps (list)
683 "Keymap alist supporting direct snippet keybindings.
685 This variable is placed in `emulation-mode-map-alists'.
687 Its elements looks like (TABLE-NAME . KEYMAP). They're
688 instantiated on `yas-reload-all' but KEYMAP is added to only when
689 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
690 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
691 defined direct keybindings to the command
692 `yas-expand-from-keymap' which then which snippet to expand.")
694 (defun yas-direct-keymaps-reload ()
695 "Force reload the direct keybinding for active snippet tables."
697 (setq yas--direct-keymaps nil)
698 (maphash #'(lambda (name table)
699 (push (cons (intern (format "yas--direct-%s" name))
700 (yas--table-direct-keymap table))
701 yas--direct-keymaps))
704 (defun yas--modes-to-activate ()
705 "Compute list of mode symbols that are active for `yas-expand'
707 (let ((modes-to-activate (list major-mode))
709 (while (setq mode (get mode 'derived-mode-parent))
710 (push mode modes-to-activate))
711 (dolist (mode (yas-extra-modes))
712 (push mode modes-to-activate))
714 (append modes-to-activate
715 (mapcan #'(lambda (mode)
716 (yas--all-parents mode))
717 modes-to-activate)))))
719 (defvar yas-minor-mode-hook nil
720 "Hook run when `yas-minor-mode' is turned on.")
723 (define-minor-mode yas-minor-mode
724 "Toggle YASnippet mode.
726 When YASnippet mode is enabled, `yas-expand', normally bound to
727 the TAB key, expands snippets of code depending on the major
730 With no argument, this command toggles the mode.
731 positive prefix argument turns on the mode.
732 Negative prefix argument turns off the mode.
735 \\{yas-minor-mode-map}"
737 ;; The indicator for the mode line.
740 (cond (yas-minor-mode
741 ;; Install the direct keymaps in `emulation-mode-map-alists'
742 ;; (we use `add-hook' even though it's not technically a hook,
743 ;; but it works). Then define variables named after modes to
744 ;; index `yas--direct-keymaps'.
746 ;; Also install the post-command-hook.
748 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
749 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
750 ;; Set the `yas--direct-%s' vars for direct keymap expansion
752 (dolist (mode (yas--modes-to-activate))
753 (let ((name (intern (format "yas--direct-%s" mode))))
754 (set-default name nil)
755 (set (make-local-variable name) t)))
758 (yas--load-pending-jits))
760 ;; Uninstall the direct keymaps and the post-command hook
762 (remove-hook 'post-command-hook 'yas--post-command-handler t)
763 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
765 (defvar yas-dont-activate '(minibufferp)
766 "If non-nil don't let `yas-global-mode' affect some buffers.
768 If a function of zero arguments, then its result is used.
770 If a list of functions, then all functions must return nil to
771 activate yas for this buffer.
773 In Emacsen <= 23, this variable is buffer-local. Because
774 `yas-minor-mode-on' is called by `yas-global-mode' after
775 executing the buffer's major mode hook, setting this variable
776 there is an effective way to define exceptions to the \"global\"
777 activation behaviour.
779 In Emacsen > 23, only the global value is used. To define
780 per-mode exceptions to the \"global\" activation behaviour, call
781 `yas-minor-mode' with a negative argument directily in the major
783 (unless (> emacs-major-version 23)
785 (make-variable-buffer-local 'yas-dont-activate)))
788 (defun yas-minor-mode-on ()
789 "Turn on YASnippet minor mode.
791 Honour `yas-dont-activate', which see."
793 ;; Check `yas-dont-activate'
794 (unless (cond ((functionp yas-dont-activate)
795 (funcall yas-dont-activate))
796 ((consp yas-dont-activate)
797 (some #'funcall yas-dont-activate))
802 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
806 (defun yas--global-mode-reload-with-jit-maybe ()
807 "Run `yas-reload-all' when `yas-global-mode' is on."
808 (when yas-global-mode (yas-reload-all)))
810 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
815 (defvar yas--font-lock-keywords
816 (append '(("^#.*$" . font-lock-comment-face))
817 lisp-font-lock-keywords
818 lisp-font-lock-keywords-1
819 lisp-font-lock-keywords-2
821 (0 font-lock-keyword-face)
822 (1 font-lock-string-face t))
824 (0 font-lock-keyword-face)
825 (1 font-lock-warning-face t))
826 ("${" font-lock-keyword-face)
827 ("$[0-9]+?" font-lock-preprocessor-face)
828 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
830 (0 font-lock-keyword-face)))))
832 (defvar snippet-mode-map
833 (let ((map (make-sparse-keymap)))
834 (easy-menu-define nil
836 "Menu used when snippet-mode is active."
838 (mapcar #'(lambda (ent)
840 (define-key map (third ent) (second ent)))
841 (vector (first ent) (second ent) t))
842 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-c")
843 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
845 "The keymap used when `snippet-mode' is active.")
848 (define-derived-mode snippet-mode text-mode "Snippet"
849 "A mode for editing yasnippets"
850 (setq font-lock-defaults '(yas--font-lock-keywords))
851 (set (make-local-variable 'require-final-newline) nil)
852 (set (make-local-variable 'comment-start) "#")
853 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
857 ;;; Internal structs for template management
859 (defstruct (yas--template (:constructor yas--make-blank-template))
860 "A template for a snippet."
870 group ;; as dictated by the #group: directive or .yas-make-groups
871 perm-group ;; as dictated by `yas-define-menu'
875 (defun yas--populate-template (template &rest args)
876 "Helper function to populate TEMPLATE with properties."
879 (position (intern (substring (symbol-name (car args)) 1))
880 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
882 (setq args (cddr args)))
885 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
886 "A table to store snippets for a particular mode.
888 Has the following fields:
892 A symbol name normally corresponding to a major mode, but can
893 also be a pseudo major-mode to be referenced in
894 `yas-extra-modes', for example.
898 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
899 a string or a vector, where the former is the snippet's trigger
900 and the latter means it's a direct keybinding. NAMEHASH is yet
901 another hash of (NAME . TEMPLATE) where NAME is the snippet's
902 name and TEMPLATE is a `yas--template' object.
904 `yas--table-direct-keymap'
906 A keymap for the snippets in this table that have direct
907 keybindings. This is kept in sync with the keyhash, i.e., all
908 the elements of the keyhash that are vectors appear here as
909 bindings to `yas-expand-from-keymap'.
911 `yas--table-uuidhash'
913 A hash table mapping snippets uuid's to the same `yas--template'
914 objects. A snippet uuid defaults to the snippet's name."
916 (hash (make-hash-table :test 'equal))
917 (uuidhash (make-hash-table :test 'equal))
919 (direct-keymap (make-sparse-keymap)))
921 (defun yas--get-template-by-uuid (mode uuid)
922 "Find the snippet template in MODE by its UUID."
923 (let* ((table (gethash mode yas--tables mode)))
925 (gethash uuid (yas--table-uuidhash table)))))
927 ;; Apropos storing/updating in TABLE, this works in two steps:
929 ;; 1. `yas--remove-template-by-uuid' removes any
930 ;; keyhash-namehash-template mappings from TABLE, grabbing the
931 ;; snippet by its uuid. Also removes mappings from TABLE's
932 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
933 ;; of potentially stale menu bindings right?.)
935 ;; 2. `yas--add-template' adds this all over again.
937 ;; Create a new or add to an existing keyhash-namehash mapping.
939 ;; For reference on understanding this, consider three snippet
942 ;; A: # name: The Foo
944 ;; # binding: C-c M-l
946 ;; B: # name: Mrs Foo
949 ;; C: # name: The Bar
950 ;; # binding: C-c M-l
955 ;; keyhash namehashes(3) yas--template structs(4)
956 ;; -----------------------------------------------------
959 ;; "foo" ---> "The Foo" ---> [yas--template A] |
960 ;; "Mrs Foo" ---> [yas--template B] |
962 ;; [C-c M-l] ---> "The Foo" -------------------------/
963 ;; "The Bar" ---> [yas--template C]
965 ;; "baz" ---> "Baz" ---> [yas--template D]
967 ;; Additionally, since uuid defaults to the name, we have a
968 ;; `yas--table-uuidhash' for TABLE
970 ;; uuidhash yas--template structs
971 ;; -------------------------------
972 ;; "The Foo" ---> [yas--template A]
973 ;; "Mrs Foo" ---> [yas--template B]
974 ;; "The Bar" ---> [yas--template C]
975 ;; "Baz" ---> [yas--template D]
977 ;; FIXME: the more I look at this data-structure the more I think I'm
978 ;; stupid. There has to be an easier way (but beware lots of code
981 (defun yas--remove-template-by-uuid (table uuid)
982 "Remove from TABLE a template identified by UUID."
983 (let ((template (gethash uuid (yas--table-uuidhash table))))
985 (let* ((name (yas--template-name template))
987 ;; Remove the name from each of the targeted namehashes
989 (maphash #'(lambda (k v)
990 (let ((template (gethash name v)))
992 (eq uuid (yas--template-uuid template)))
994 (when (zerop (hash-table-count v))
995 (push k empty-keys)))))
996 (yas--table-hash table))
997 ;; Remove the namehash themselves if they've become empty
999 (dolist (key empty-keys)
1001 (define-key (yas--table-direct-keymap table) key nil))
1002 (remhash key (yas--table-hash table)))
1004 ;; Finally, remove the uuid from the uuidhash
1006 (remhash uuid (yas--table-uuidhash table))))))
1008 (defun yas--add-template (table template)
1009 "Store in TABLE the snippet template TEMPLATE.
1011 KEY can be a string (trigger key) of a vector (direct
1013 (let ((name (yas--template-name template))
1014 (key (yas--template-key template))
1015 (keybinding (yas--template-keybinding template))
1016 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1017 (dolist (k (remove nil (list key keybinding)))
1021 (yas--table-hash table))
1023 (make-hash-table :test 'equal)
1024 (yas--table-hash table))))
1026 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1028 ;; Update TABLE's `yas--table-uuidhash'
1029 (puthash (yas--template-uuid template)
1031 (yas--table-uuidhash table))))
1033 (defun yas--update-template (table template)
1034 "Add or update TEMPLATE in TABLE.
1036 Also takes care of adding and updating to the associated menu."
1037 ;; Remove from table by uuid
1039 (yas--remove-template-by-uuid table (yas--template-uuid template))
1040 ;; Add to table again
1042 (yas--add-template table template)
1043 ;; Take care of the menu
1046 (yas--update-template-menu table template)))
1048 (defun yas--update-template-menu (table template)
1049 "Update every menu-related for TEMPLATE."
1050 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1051 (key (yas--template-key template))
1052 (keybinding (yas--template-keybinding template)))
1053 ;; The snippet might have changed name or keys, so update
1054 ;; user-visible strings
1056 (unless (eq (cdr menu-binding-pair) :none)
1057 ;; the menu item name
1059 (setf (cadar menu-binding-pair) (yas--template-name template))
1060 ;; the :keys information (also visible to the user)
1061 (setf (getf (cdr (car menu-binding-pair)) :keys)
1062 (or (and keybinding (key-description keybinding))
1063 (and key (concat key yas-trigger-symbol))))))
1064 (unless (yas--template-menu-managed-by-yas-define-menu template)
1066 (yas--menu-keymap-get-create (yas--table-mode table)
1067 (mapcar #'yas--table-mode
1068 (yas--table-parents table))))
1069 (group (yas--template-group template)))
1070 ;; Remove from menu keymap
1072 (assert menu-keymap)
1073 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1075 ;; Add necessary subgroups as necessary.
1077 (dolist (subgroup group)
1078 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1079 (unless (and subgroup-keymap
1080 (keymapp subgroup-keymap))
1081 (setq subgroup-keymap (make-sparse-keymap))
1082 (define-key menu-keymap (vector (make-symbol subgroup))
1083 `(menu-item ,subgroup ,subgroup-keymap)))
1084 (setq menu-keymap subgroup-keymap)))
1086 ;; Add this entry to the keymap
1088 (define-key menu-keymap
1089 (vector (make-symbol (yas--template-uuid template)))
1090 (car (yas--template-menu-binding-pair template))))))
1092 (defun yas--namehash-templates-alist (namehash)
1093 "Return NAMEHASH as an alist."
1095 (maphash #'(lambda (k v)
1096 (push (cons k v) alist))
1100 (defun yas--fetch (table key)
1101 "Fetch templates in TABLE by KEY.
1103 Return a list of cons (NAME . TEMPLATE) where NAME is a
1104 string and TEMPLATE is a `yas--template' structure."
1105 (let* ((keyhash (yas--table-hash table))
1106 (namehash (and keyhash (gethash key keyhash))))
1108 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1111 ;;; Filtering/condition logic
1113 (defun yas--eval-condition (condition)
1120 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1124 (defun yas--filter-templates-by-condition (templates)
1125 "Filter the templates using the applicable condition.
1127 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1128 string and TEMPLATE is a `yas--template' structure.
1130 This function implements the rules described in
1131 `yas-buffer-local-condition'. See that variables documentation."
1132 (let ((requirement (yas--require-template-specific-condition-p)))
1133 (if (eq requirement 'always)
1135 (remove-if-not #'(lambda (pair)
1136 (yas--template-can-expand-p
1137 (yas--template-condition (cdr pair)) requirement))
1140 (defun yas--require-template-specific-condition-p ()
1141 "Decide if this buffer requests/requires snippet-specific
1142 conditions to filter out potential expansions."
1143 (if (eq 'always yas-buffer-local-condition)
1145 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1146 (yas--eval-condition yas-buffer-local-condition))
1147 yas-buffer-local-condition)))
1148 (when local-condition
1149 (if (eq local-condition t)
1151 (and (consp local-condition)
1152 (eq 'require-snippet-condition (car local-condition))
1153 (symbolp (cdr local-condition))
1154 (cdr local-condition)))))))
1156 (defun yas--template-can-expand-p (condition requirement)
1157 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1158 (let* ((result (or (null condition)
1159 (yas--eval-condition condition))))
1160 (cond ((eq requirement t)
1163 (eq requirement result)))))
1165 (defun yas--all-parents (mode)
1166 "Return a list of all parent modes of MODE."
1167 (or (gethash mode yas--ancestors)
1169 (labels ((yas--all-parents-1
1171 (cond ((memq m seen)
1173 "Cyclic parenthood: mode %s has already seen as a parent of mode %s"
1177 (let* ((parents (gethash m yas--parents)))
1178 (setq seen (append seen parents))
1179 (append parents (mapcan #'yas--all-parents-1 parents)))))))
1180 (puthash mode (yas--all-parents-1 mode)
1183 (defun yas--table-templates (table)
1186 (maphash #'(lambda (_key namehash)
1187 (maphash #'(lambda (name template)
1188 (push (cons name template) acc))
1190 (yas--table-hash table))
1191 (yas--filter-templates-by-condition acc))))
1193 (defun yas--current-key ()
1194 "Get the key under current position.
1195 A key is used to find the template of a snippet in the current snippet-table."
1196 (let ((start (point))
1198 (syntaxes yas-key-syntaxes)
1202 (while (and (not done) syntaxes)
1203 (setq syntax (car syntaxes))
1204 (setq syntaxes (cdr syntaxes))
1206 (skip-syntax-backward syntax)
1207 (setq start (point)))
1209 (mapcan #'(lambda (table)
1210 (yas--fetch table (buffer-substring-no-properties start end)))
1211 (yas--get-snippet-tables)))
1220 (defun yas--table-all-keys (table)
1221 "Get trigger keys of all active snippets in TABLE."
1223 (maphash #'(lambda (key namehash)
1224 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1226 (yas--table-hash table))
1229 (defun yas--table-mode (table)
1230 (intern (yas--table-name table)))
1233 ;;; Internal functions and macros:
1235 (defun yas--real-mode? (mode)
1236 "Try to find out if MODE is a real mode.
1238 The MODE bound to a function (like `c-mode') is considered real
1239 mode. Other well known mode like `ruby-mode' which is not part of
1240 Emacs might not bound to a function until it is loaded. So
1241 yasnippet keeps a list of modes like this to help the judgment."
1243 (find mode yas--known-modes)))
1245 (defun yas--eval-lisp (form)
1246 "Evaluate FORM and convert the result to string."
1247 (let ((retval (catch 'yas--exception
1253 (let ((result (eval form)))
1255 (format "%s" result))))))
1256 (error (if yas-good-grace
1257 (yas--format "elisp error! %s" (error-message-string err))
1258 (error (yas--format "elisp error: %s"
1259 (error-message-string err)))))))))
1260 (when (and (consp retval)
1261 (eq 'yas--exception (car retval)))
1262 (error (cdr retval)))
1265 (defun yas--eval-lisp-no-saves (form)
1268 (error (if yas-good-grace
1269 (yas--format "elisp error! %s" (error-message-string err))
1270 (error (yas--format "elisp error: %s"
1271 (error-message-string err)))))))
1273 (defun yas--read-lisp (string &optional nil-on-error)
1274 "Read STRING as a elisp expression and return it.
1276 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1277 return an expression that when evaluated will issue an error."
1280 (error (and (not nil-on-error)
1281 `(error (error-message-string ,err))))))
1283 (defun yas--read-keybinding (keybinding)
1284 "Read KEYBINDING as a snippet keybinding, return a vector."
1285 (when (and keybinding
1286 (not (string-match "keybinding" keybinding)))
1288 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1290 (read-kbd-macro keybinding 'need-vector))))
1293 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1294 keybinding (error-message-string err))
1297 (defvar yas-extra-modes nil
1298 "If non-nil, also lookup snippets for this/these modes.
1300 Can be a symbol or a list of symbols.
1302 This variable probably makes more sense as buffer-local, so
1303 ensure your use `make-local-variable' when you set it.")
1304 (defun yas-extra-modes ()
1305 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1306 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1308 (defun yas--table-get-create (mode)
1309 "Get or create the snippet table corresponding to MODE."
1310 (let ((table (gethash mode
1313 (setq table (yas--make-snippet-table (symbol-name mode)))
1314 (puthash mode table yas--tables)
1315 (push (cons (intern (format "yas--direct-%s" mode))
1316 (yas--table-direct-keymap table))
1317 yas--direct-keymaps))
1320 (defun yas--get-snippet-tables ()
1321 "Get snippet tables for current buffer.
1323 Return a list of `yas--table' objects. The list of modes to
1324 consider is returned by `yas--modes-to-activate'"
1326 (mapcar #'(lambda (name)
1327 (gethash name yas--tables))
1328 (yas--modes-to-activate))))
1330 (defun yas--menu-keymap-get-create (mode &optional parents)
1331 "Get or create the menu keymap for MODE and its PARENTS.
1333 This may very well create a plethora of menu keymaps and arrange
1334 them all in `yas--menu-table'"
1335 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1336 (puthash mode (make-sparse-keymap) yas--menu-table))))
1337 (mapc #'yas--menu-keymap-get-create parents)
1338 (define-key yas--minor-mode-menu (vector mode)
1339 `(menu-item ,(symbol-name mode) ,menu-keymap
1340 :visible (yas--show-menu-p ',mode)))
1344 (defmacro yas--called-interactively-p (&optional kind)
1345 "A backward-compatible version of `called-interactively-p'.
1347 Optional KIND is as documented at `called-interactively-p'
1348 in GNU Emacs 24.1 or higher."
1349 (if (string< emacs-version "24.1")
1350 '(called-interactively-p)
1351 `(called-interactively-p ,kind)))
1354 ;;; Template-related and snippet loading functions
1356 (defun yas--parse-template (&optional file)
1357 "Parse the template in the current buffer.
1359 Optional FILE is the absolute file name of the file being
1362 Optional GROUP is the group where the template is to go,
1363 otherwise we attempt to calculate it from FILE.
1365 Return a snippet-definition, i.e. a list
1367 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1369 If the buffer contains a line of \"# --\" then the contents above
1370 this line are ignored. Directives can set most of these with the syntax:
1372 # directive-name : directive-value
1374 Here's a list of currently recognized directives:
1385 (goto-char (point-min))
1386 (let* ((type 'snippet)
1388 (file-name-nondirectory file)))
1394 (yas--calculate-group file)))
1398 (if (re-search-forward "^# --\n" nil t)
1399 (progn (setq template
1400 (buffer-substring-no-properties (point)
1402 (setq bound (point))
1403 (goto-char (point-min))
1404 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1405 (when (string= "uuid" (match-string-no-properties 1))
1406 (setq uuid (match-string-no-properties 2)))
1407 (when (string= "type" (match-string-no-properties 1))
1408 (setq type (if (string= "command" (match-string-no-properties 2))
1411 (when (string= "key" (match-string-no-properties 1))
1412 (setq key (match-string-no-properties 2)))
1413 (when (string= "name" (match-string-no-properties 1))
1414 (setq name (match-string-no-properties 2)))
1415 (when (string= "condition" (match-string-no-properties 1))
1416 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1417 (when (string= "group" (match-string-no-properties 1))
1418 (setq group (match-string-no-properties 2)))
1419 (when (string= "expand-env" (match-string-no-properties 1))
1420 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1422 (when (string= "binding" (match-string-no-properties 1))
1423 (setq binding (match-string-no-properties 2)))))
1425 (buffer-substring-no-properties (point-min) (point-max))))
1426 (unless (or key binding)
1427 (setq key (and file (file-name-nondirectory file))))
1428 (when (eq type 'command)
1429 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1431 (setq group (split-string group "\\.")))
1432 (list key template name condition group expand-env file binding uuid)))
1434 (defun yas--calculate-group (file)
1435 "Calculate the group for snippet file path FILE."
1436 (let* ((dominating-dir (locate-dominating-file file
1437 ".yas-make-groups"))
1438 (extra-path (and dominating-dir
1439 (replace-regexp-in-string (concat "^"
1440 (expand-file-name dominating-dir))
1442 (expand-file-name file))))
1443 (extra-dir (and extra-path
1444 (file-name-directory extra-path)))
1445 (group (and extra-dir
1446 (replace-regexp-in-string "/"
1448 (directory-file-name extra-dir)))))
1451 (defun yas--subdirs (directory &optional filep)
1452 "Return subdirs or files of DIRECTORY according to FILEP."
1453 (remove-if (lambda (file)
1454 (or (string-match "^\\."
1455 (file-name-nondirectory file))
1456 (string-match "^#.*#$"
1457 (file-name-nondirectory file))
1459 (file-name-nondirectory file))
1461 (file-directory-p file)
1462 (not (file-directory-p file)))))
1463 (directory-files directory t)))
1465 (defun yas--make-menu-binding (template)
1466 (let ((mode (yas--table-mode (yas--template-table template))))
1467 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1469 (defun yas--expand-or-visit-from-menu (mode uuid)
1470 (let* ((table (yas--table-get-create mode))
1471 (yas--current-template (and table
1472 (gethash uuid (yas--table-uuidhash table)))))
1473 (when yas--current-template
1474 (if yas-visit-from-menu
1475 (yas--visit-snippet-file-1 yas--current-template)
1476 (let ((where (if (region-active-p)
1477 (cons (region-beginning) (region-end))
1478 (cons (point) (point)))))
1479 (yas-expand-snippet (yas--template-content yas--current-template)
1482 (yas--template-expand-env yas--current-template)))))))
1484 (defun yas--key-from-desc (text)
1485 "Return a yasnippet key from a description string TEXT."
1486 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1489 ;;; Popping up for keys and templates
1491 (defvar yas--x-pretty-prompt-templates nil
1492 "If non-nil, attempt to prompt for templates like TextMate.")
1495 (defun yas--prompt-for-template (templates &optional prompt)
1496 "Interactively choose a template from the list TEMPLATES.
1498 TEMPLATES is a list of `yas--template'.
1500 Optional PROMPT sets the prompt to use."
1503 (sort templates #'(lambda (t1 t2)
1504 (< (length (yas--template-name t1))
1505 (length (yas--template-name t2))))))
1506 (if yas--x-pretty-prompt-templates
1507 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1508 (some #'(lambda (fn)
1509 (funcall fn (or prompt "Choose a snippet: ")
1511 #'yas--template-name))
1512 yas-prompt-functions))))
1514 (defun yas--prompt-for-keys (keys &optional prompt)
1515 "Interactively choose a template key from the list KEYS.
1517 Optional PROMPT sets the prompt to use."
1519 (some #'(lambda (fn)
1520 (funcall fn (or prompt "Choose a snippet key: ") keys))
1521 yas-prompt-functions)))
1523 (defun yas--prompt-for-table (tables &optional prompt)
1524 "Interactively choose a table from the list TABLES.
1526 Optional PROMPT sets the prompt to use."
1528 (some #'(lambda (fn)
1529 (funcall fn (or prompt "Choose a snippet table: ")
1532 yas-prompt-functions)))
1534 (defun yas-x-prompt (prompt choices &optional display-fn)
1535 "Display choices in a x-window prompt."
1536 ;; FIXME: HACK: if we notice that one of the objects in choices is
1537 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1539 ;; This would be better implemented by passing CHOICES as a
1540 ;; structured tree rather than a list. Modifications would go as far
1541 ;; up as `yas--all-templates' I think.
1543 (when (and window-system choices)
1545 (let (menu d) ;; d for display
1547 (setq d (or (and display-fn (funcall display-fn c))
1550 (push (cons (concat " " d) c) menu))
1552 (push (car d) menu))))
1553 (setq menu (list prompt (push "title" menu)))
1554 (x-popup-menu (if (fboundp 'posn-at-point)
1555 (let ((x-y (posn-x-y (posn-at-point (point)))))
1556 (list (list (+ (car x-y) 10)
1564 (defun yas--x-pretty-prompt-templates (prompt templates)
1565 "Display TEMPLATES, grouping neatly by table name."
1566 (let ((organized (make-hash-table :test #'equal))
1570 (dolist (tl templates)
1571 (puthash (yas--template-table tl)
1573 (gethash (yas--template-table tl) organized))
1575 (setq more-than-one-table (> (hash-table-count organized) 1))
1576 (setq prefix (if more-than-one-table
1578 (if more-than-one-table
1579 (maphash #'(lambda (table templates)
1580 (push (yas--table-name table) menu)
1581 (dolist (tl templates)
1582 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1583 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1585 (setq menu (nreverse menu))
1586 (or (x-popup-menu (if (fboundp 'posn-at-point)
1587 (let ((x-y (posn-x-y (posn-at-point (point)))))
1588 (list (list (+ (car x-y) 10)
1592 (list prompt (push "title" menu)))
1595 (defun yas-ido-prompt (prompt choices &optional display-fn)
1596 (when (and (fboundp 'ido-completing-read)
1597 (or (>= emacs-major-version 24)
1599 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1601 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1602 (when (fboundp 'dropdown-list)
1603 (let (formatted-choices
1607 (dolist (choice choices)
1608 (setq d (or (and display-fn (funcall display-fn choice))
1611 (push d formatted-choices)
1612 (push choice filtered-choices)))
1614 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1616 (nth n filtered-choices)
1619 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1620 (let (formatted-choices
1624 (completion-fn (or completion-fn
1625 #'completing-read)))
1626 (dolist (choice choices)
1627 (setq d (or (and display-fn (funcall display-fn choice))
1630 (push d formatted-choices)
1631 (push choice filtered-choices)))
1632 (setq chosen (and formatted-choices
1633 (funcall completion-fn prompt
1639 (let ((position (or (and chosen
1640 (position chosen formatted-choices :test #'string=))
1642 (nth position filtered-choices))))
1644 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1648 ;;; Defining snippets
1649 ;; This consists of creating and registering `yas--template' objects in the
1653 (defvar yas--creating-compiled-snippets nil)
1655 (defun yas--define-snippets-1 (snippet snippet-table)
1656 "Helper for `yas-define-snippets'."
1657 ;; X) Calculate some more defaults on the values returned by
1658 ;; `yas--parse-template'.
1660 (let* ((file (seventh snippet))
1662 (name (or (third snippet)
1664 (file-name-directory file))))
1665 (condition (fourth snippet))
1666 (group (fifth snippet))
1667 (keybinding (yas--read-keybinding (eighth snippet)))
1668 (uuid (or (ninth snippet)
1670 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1671 (yas--make-blank-template))))
1672 ;; X) populate the template object
1674 (yas--populate-template template
1675 :table snippet-table
1677 :content (second snippet)
1680 :condition condition
1681 :expand-env (sixth snippet)
1682 :file (seventh snippet)
1683 :keybinding keybinding
1685 ;; X) Update this template in the appropriate table. This step
1686 ;; also will take care of adding the key indicators in the
1687 ;; templates menu entry, if any
1689 (yas--update-template snippet-table template)
1690 ;; X) Return the template
1695 (defun yas-define-snippets (mode snippets)
1696 "Define SNIPPETS for MODE.
1698 SNIPPETS is a list of snippet definitions, each taking the
1701 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1703 Within these, only KEY and TEMPLATE are actually mandatory.
1705 TEMPLATE might be a Lisp form or a string, depending on whether
1706 this is a snippet or a snippet-command.
1708 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1709 been `yas--read-lisp'-ed and will eventually be
1710 `yas--eval-lisp'-ed.
1712 The remaining elements are strings.
1714 FILE is probably of very little use if you're programatically
1717 UUID is the snippets \"unique-id\". Loading a second snippet file
1718 with the same uuid replaced the previous snippet.
1720 You can use `yas--parse-template' to return such lists based on
1721 the current buffers contents."
1722 (if yas--creating-compiled-snippets
1724 (insert ";;; Snippet definitions:\n;;;\n")
1725 (let ((literal-snippets (list))
1727 (dolist (snippet snippets)
1728 (let ((key (nth 0 snippet))
1729 (template-content (nth 1 snippet))
1730 (name (nth 2 snippet))
1731 (condition (nth 3 snippet))
1732 (group (nth 4 snippet))
1733 (expand-env (nth 5 snippet))
1734 (file nil) ;; omit on purpose
1735 (binding (nth 7 snippet))
1736 (uuid (nth 8 snippet)))
1747 (insert (pp-to-string
1748 `(yas-define-snippets ',mode ',literal-snippets)))
1751 (let ((snippet-table (yas--table-get-create mode))
1753 (dolist (snippet snippets)
1754 (setq template (yas--define-snippets-1 snippet
1759 ;;; Loading snippets from files
1761 (defun yas--load-yas-setup-file (file)
1762 (if (not yas--creating-compiled-snippets)
1764 (load file 'noerror)
1765 (let ((elfile (concat file ".el")))
1766 (when (file-exists-p elfile)
1767 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1768 (insert-file-contents elfile)
1769 (goto-char (point-max))))))
1771 (defun yas--define-parents (mode parents)
1772 "Add PARENTS to the list of MODE's parents."
1773 (puthash mode (remove-duplicates
1775 (gethash mode yas--parents)))
1778 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1779 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1781 Below TOP-LEVEL-DIR each directory should be a mode name.
1783 Optional USE-JIT use jit-loading of snippets."
1784 (interactive "DSelect the root directory: ni\np")
1785 (unless yas-snippet-dirs
1786 (setq yas-snippet-dirs top-level-dir))
1787 (dolist (dir (yas--subdirs top-level-dir))
1788 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1789 (concat dir "/dummy")))
1790 (mode-sym (car major-mode-and-parents))
1791 (parents (cdr major-mode-and-parents)))
1792 ;; Attention: The parents and the menus are already defined
1793 ;; here, even if the snippets are later jit-loaded.
1795 ;; * We need to know the parents at this point since entering a
1796 ;; given mode should jit load for its parents
1797 ;; immediately. This could be reviewed, the parents could be
1798 ;; discovered just-in-time-as well
1800 ;; * We need to create the menus here to support the `full'
1801 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1803 (yas--define-parents mode-sym parents)
1804 (yas--menu-keymap-get-create mode-sym)
1805 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1806 (yas--load-directory-1 ',dir ',mode-sym))))
1808 (not (some #'(lambda (buffer)
1809 (with-current-buffer buffer
1810 ;; FIXME: Shouldn't this use derived-mode-p?
1811 (when (eq major-mode mode-sym)
1812 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1815 (yas--schedule-jit mode-sym fun)
1818 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1820 (defun yas--load-directory-1 (directory mode-sym)
1821 "Recursively load snippet templates from DIRECTORY."
1822 (if yas--creating-compiled-snippets
1823 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1825 (with-temp-file output-file
1826 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1828 (yas--load-directory-2 directory mode-sym)
1829 (insert (format ";;; Do not edit! File generated at %s\n"
1830 (current-time-string)))))
1832 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1833 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1834 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1835 (yas--message 2 "Loading snippet files from %s" directory)
1836 (yas--load-directory-2 directory mode-sym)))))
1838 (defun yas--load-directory-2 (directory mode-sym)
1839 ;; Load .yas-setup.el files wherever we find them
1841 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1842 (let* ((default-directory directory)
1844 ;; load the snippet files
1847 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1848 (when (file-readable-p file)
1849 (insert-file-contents file nil nil nil t)
1850 (push (yas--parse-template file)
1853 (yas-define-snippets mode-sym
1855 ;; now recurse to a lower level
1857 (dolist (subdir (yas--subdirs directory))
1858 (yas--load-directory-2 subdir
1861 (defun yas--load-snippet-dirs (&optional nojit)
1862 "Reload the directories listed in `yas-snippet-dirs' or
1863 prompt the user to select one."
1865 (if yas-snippet-dirs
1866 (dolist (directory (reverse (yas-snippet-dirs)))
1867 (cond ((file-directory-p directory)
1868 (yas-load-directory directory (not nojit))
1870 (yas--message 3 "Loaded %s" directory)
1871 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1873 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1874 (call-interactively 'yas-load-directory))
1877 (defun yas-reload-all (&optional interactive)
1878 "Reload all snippets and rebuild the YASnippet menu.
1880 When called interactively force immediate reload of all known
1881 snippets under `yas-snippet-dirs', otherwise use just-in-time
1886 (snippet-editing-buffers
1887 (remove-if-not #'(lambda (buffer)
1888 (with-current-buffer buffer yas--editing-template))
1890 ;; Warn if there are buffers visiting snippets, since reloading will break
1891 ;; any on-line editing of those buffers.
1893 (when snippet-editing-buffers
1895 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1896 (mapc #'kill-buffer snippet-editing-buffers)
1897 (yas--message 1 "Aborted reload...")
1899 ;; in a non-interactive use, at least set
1900 ;; `yas--editing-template' to nil, make it guess it next time around
1901 (mapc #'(lambda (buffer)
1902 (with-current-buffer buffer
1903 (kill-local-variable 'yas--editing-template)))
1906 ;; Empty all snippet tables and parenting info
1908 (setq yas--tables (make-hash-table))
1909 (setq yas--parents (make-hash-table))
1910 (setq yas--ancestors (make-hash-table))
1912 ;; Before killing `yas--menu-table' use its keys to cleanup the
1913 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1914 ;; up `yas-minor-mode-map', which points to it)
1916 (maphash #'(lambda (menu-symbol _keymap)
1917 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1919 ;; Now empty `yas--menu-table' as well
1920 (setq yas--menu-table (make-hash-table))
1922 ;; Cancel all pending 'yas--scheduled-jit-loads'
1924 (setq yas--scheduled-jit-loads (make-hash-table))
1926 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1927 ;; the user to select one.
1929 (setq errors (yas--load-snippet-dirs interactive))
1930 ;; Reload the direct keybindings
1932 (yas-direct-keymaps-reload)
1934 (yas--message 3 "Reloaded everything%s...%s."
1935 (if interactive "" " (snippets will load just-in-time)")
1936 (if errors " (some errors, check *Messages*)" "")))))
1938 (defun yas--load-pending-jits ()
1939 (dolist (mode (yas--modes-to-activate))
1940 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1941 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1943 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1945 (remhash mode yas--scheduled-jit-loads))))
1947 ;; (when (<= emacs-major-version 22)
1948 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1950 (defun yas--quote-string (string)
1951 "Escape and quote STRING.
1952 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1954 (replace-regexp-in-string "[\\\"]"
1960 ;;; Snippet compilation function
1962 (defun yas--initialize ()
1963 "For backward compatibility, enable `yas-minor-mode' globally."
1964 (yas-global-mode 1))
1966 (defun yas-compile-directory (top-level-dir)
1967 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1969 This works by stubbing a few functions, then calling
1970 `yas-load-directory'."
1971 (interactive "DTop level snippet directory?")
1972 (let ((yas--creating-compiled-snippets t))
1973 (yas-load-directory top-level-dir nil)))
1975 (defun yas-recompile-all ()
1976 "Compile every dir in `yas-snippet-dirs'."
1978 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1984 (defvar yas--scheduled-jit-loads (make-hash-table)
1985 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1987 (defun yas--schedule-jit (mode fun)
1988 (push fun (gethash mode yas--scheduled-jit-loads)))
1992 ;;; Some user level functions
1996 (message (concat "yasnippet (version "
1998 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2001 ;;; Apropos snippet menu:
2003 ;; The snippet menu keymaps are store by mode in hash table called
2004 ;; `yas--menu-table'. They are linked to the main menu in
2005 ;; `yas--menu-keymap-get-create' and are initially created empty,
2006 ;; reflecting the table hierarchy.
2008 ;; They can be populated in two mutually exclusive ways: (1) by
2009 ;; reading `yas--template-group', which in turn is populated by the "#
2010 ;; group:" directives of the snippets or the ".yas-make-groups" file
2011 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2012 ;; menu structure based on snippets uuids.
2014 ;; Both situations are handled in `yas--update-template-menu', which
2015 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2016 ;; that can tell between the two situations.
2020 ;; * if `yas-define-menu' is used it must run before
2021 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2022 ;; duplicate entries. The `yas--template' objects are created in
2023 ;; `yas-define-menu', holding nothing but the menu entry,
2024 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2025 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2026 ;; part is then stored in the menu keymap itself which make the item
2027 ;; appear to the user. These limitations could probably be revised.
2029 ;; * The `yas--template-perm-group' slot is only used in
2030 ;; `yas-describe-tables'.
2032 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2033 "Get TEMPLATE's menu binding or assign it a new one.
2035 TYPE may be `:stay', signaling this menu binding should be
2036 static in the menu."
2037 (or (yas--template-menu-binding-pair template)
2038 (let (;; (key (yas--template-key template))
2039 ;; (keybinding (yas--template-keybinding template))
2041 (setf (yas--template-menu-binding-pair template)
2042 (cons `(menu-item ,(or (yas--template-name template)
2043 (yas--template-uuid template))
2044 ,(yas--make-menu-binding template)
2047 (defun yas--template-menu-managed-by-yas-define-menu (template)
2048 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2049 (cdr (yas--template-menu-binding-pair template)))
2052 (defun yas--show-menu-p (mode)
2053 (cond ((eq yas-use-menu 'abbreviate)
2055 (mapcar #'(lambda (table)
2056 (yas--table-mode table))
2057 (yas--get-snippet-tables))))
2058 ((eq yas-use-menu 'full)
2060 ((eq yas-use-menu t)
2063 (defun yas--delete-from-keymap (keymap uuid)
2064 "Recursively delete items with UUID from KEYMAP and its submenus."
2066 ;; XXX: This used to skip any submenus named \"parent mode\"
2068 ;; First of all, recursively enter submenus, i.e. the tree is
2069 ;; searched depth first so that stale submenus can be found in the
2072 (mapc #'(lambda (item)
2073 (when (and (listp (cdr item))
2074 (keymapp (third (cdr item))))
2075 (yas--delete-from-keymap (third (cdr item)) uuid)))
2077 ;; Set the uuid entry to nil
2079 (define-key keymap (vector (make-symbol uuid)) nil)
2080 ;; Destructively modify keymap
2082 (setcdr keymap (delete-if #'(lambda (item)
2083 (or (null (cdr item))
2084 (and (keymapp (third (cdr item)))
2085 (null (cdr (third (cdr item)))))))
2088 (defun yas-define-menu (mode menu &optional omit-items)
2089 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2091 MENU is a list, its elements can be:
2093 - (yas-item UUID) : Creates an entry the snippet identified with
2094 UUID. The menu entry for a snippet thus identified is
2095 permanent, i.e. it will never move (be reordered) in the menu.
2097 - (yas-separator) : Creates a separator
2099 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2100 SUBMENU has the same form as MENU. NAME is also added to the
2101 list of groups of the snippets defined thereafter.
2103 OMIT-ITEMS is a list of snippet uuid's that will always be
2104 omitted from MODE's menu, even if they're manually loaded.
2106 This function does nothing if `yas-use-menu' is nil."
2108 (let* ((table (yas--table-get-create mode))
2109 (hash (yas--table-uuidhash table)))
2110 (yas--define-menu-1 table
2111 (yas--menu-keymap-get-create mode)
2114 (dolist (uuid omit-items)
2115 (let ((template (or (gethash uuid hash)
2116 (yas--populate-template (puthash uuid
2117 (yas--make-blank-template)
2121 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2123 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2124 "Helper for `yas-define-menu'."
2125 (dolist (e (reverse menu))
2126 (cond ((eq (first e) 'yas-item)
2127 (let ((template (or (gethash (second e) uuidhash)
2128 (yas--populate-template (puthash (second e)
2129 (yas--make-blank-template)
2132 :perm-group group-list
2133 :uuid (second e)))))
2134 (define-key menu-keymap (vector (gensym))
2135 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2136 ((eq (first e) 'yas-submenu)
2137 (let ((subkeymap (make-sparse-keymap)))
2138 (define-key menu-keymap (vector (gensym))
2139 `(menu-item ,(second e) ,subkeymap))
2140 (yas--define-menu-1 table
2144 (append group-list (list (second e))))))
2145 ((eq (first e) 'yas-separator)
2146 (define-key menu-keymap (vector (gensym))
2147 '(menu-item "----")))
2149 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2151 (defun yas--define (mode key template &optional name condition group)
2152 "Define a snippet. Expanding KEY into TEMPLATE.
2154 NAME is a description to this template. Also update the menu if
2155 `yas-use-menu' is t. CONDITION is the condition attached to
2156 this snippet. If you attach a condition to a snippet, then it
2157 will only be expanded when the condition evaluated to non-nil."
2158 (yas-define-snippets mode
2159 (list (list key template name condition group))))
2161 (defun yas-hippie-try-expand (first-time?)
2162 "Integrate with hippie expand.
2164 Just put this function in `hippie-expand-try-functions-list'."
2165 (when yas-minor-mode
2166 (if (not first-time?)
2167 (let ((yas-fallback-behavior 'return-nil))
2173 ;;; Apropos condition-cache:
2178 (defvar yas--condition-cache-timestamp nil)
2179 (defmacro yas-define-condition-cache (func doc &rest body)
2180 "Define a function FUNC with doc DOC and body BODY.
2181 BODY is executed at most once every snippet expansion attempt, to check
2182 expansion conditions.
2184 It doesn't make any sense to call FUNC programatically."
2185 `(defun ,func () ,(if (and doc
2188 "\n\nFor use in snippets' conditions. Within each
2189 snippet-expansion routine like `yas-expand', computes actual
2190 value for the first time then always returns a cached value.")
2191 (setq body (cons doc body))
2193 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2194 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2195 (cdr timestamp-and-value)
2196 (let ((new-value (progn
2199 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2202 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2203 (defun yas-expand-from-trigger-key (&optional field)
2204 "Expand a snippet before point.
2206 If no snippet expansion is possible, fall back to the behaviour
2207 defined in `yas-fallback-behavior'.
2209 Optional argument FIELD is for non-interactive use and is an
2210 object satisfying `yas--field-p' to restrict the expansion to."
2212 (setq yas--condition-cache-timestamp (current-time))
2213 (let (templates-and-pos)
2214 (unless (and yas-expand-only-for-last-commands
2215 (not (member last-command yas-expand-only-for-last-commands)))
2216 (setq templates-and-pos (if field
2218 (narrow-to-region (yas--field-start field)
2219 (yas--field-end field))
2221 (yas--current-key))))
2222 (if (and templates-and-pos
2223 (first templates-and-pos))
2224 (yas--expand-or-prompt-for-template (first templates-and-pos)
2225 (second templates-and-pos)
2226 (third templates-and-pos))
2229 (defun yas-expand-from-keymap ()
2230 "Directly expand some snippets, searching `yas--direct-keymaps'.
2232 If expansion fails, execute the previous binding for this key"
2234 (setq yas--condition-cache-timestamp (current-time))
2235 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2236 universal-argument-num-events
2238 (templates (mapcan #'(lambda (table)
2239 (yas--fetch table vec))
2240 (yas--get-snippet-tables))))
2242 (yas--expand-or-prompt-for-template templates)
2243 (let ((yas-fallback-behavior 'call-other-command))
2246 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2247 "Expand one of TEMPLATES from START to END.
2249 Prompt the user if TEMPLATES has more than one element, else
2250 expand immediately. Common gateway for
2251 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2252 (let ((yas--current-template (or (and (rest templates) ;; more than one
2253 (yas--prompt-for-template (mapcar #'cdr templates)))
2255 (when yas--current-template
2256 (yas-expand-snippet (yas--template-content yas--current-template)
2259 (yas--template-expand-env yas--current-template)))))
2261 ;; Apropos the trigger key and the fallback binding:
2263 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2264 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2265 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2266 ;; improve this explanation.
2268 (defun yas--fallback ()
2269 "Fallback after expansion has failed.
2271 Common gateway for `yas-expand-from-trigger-key' and
2272 `yas-expand-from-keymap'."
2273 (cond ((eq yas-fallback-behavior 'return-nil)
2276 ((eq yas-fallback-behavior 'call-other-command)
2277 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2278 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2279 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2280 (setq this-original-command beyond-yasnippet)
2281 (call-interactively beyond-yasnippet)))
2282 ((and (listp yas-fallback-behavior)
2283 (cdr yas-fallback-behavior)
2284 (eq 'apply (car yas-fallback-behavior)))
2285 (if (cddr yas-fallback-behavior)
2286 (apply (cadr yas-fallback-behavior)
2287 (cddr yas-fallback-behavior))
2288 (when (commandp (cadr yas-fallback-behavior))
2289 (setq this-command (cadr yas-fallback-behavior))
2290 (call-interactively (cadr yas-fallback-behavior)))))
2292 ;; also return nil if all the other fallbacks have failed
2295 (defun yas--keybinding-beyond-yasnippet ()
2297 (let* ((yas-minor-mode nil)
2298 (yas--direct-keymaps nil)
2299 (keys (this-single-command-keys)))
2300 (or (key-binding keys t)
2301 (key-binding (yas--fallback-translate-input keys) t))))
2303 (defun yas--fallback-translate-input (keys)
2304 "Emulate `read-key-sequence', at least what I think it does.
2306 Keys should be an untranslated key vector. Returns a translated
2307 vector of keys. FIXME not thoroughly tested."
2310 (while (< i (length keys))
2312 (translated local-function-key-map))
2313 (while (and (< j (length keys))
2315 (keymapp translated))
2316 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2318 (setq retval (vconcat retval (cond ((symbolp translated)
2320 ((vectorp translated)
2323 (substring keys i j)))))
2328 ;;; Utils for snippet development:
2330 (defun yas--all-templates (tables)
2331 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2333 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2334 `yas-buffer-local-condition'"
2335 (when yas-choose-tables-first
2336 (setq tables (list (yas--prompt-for-table tables))))
2338 (if yas-choose-keys-first
2339 (let ((key (yas--prompt-for-keys
2340 (mapcan #'yas--table-all-keys tables))))
2342 (mapcan #'(lambda (table)
2343 (yas--fetch table key))
2345 (remove-duplicates (mapcan #'yas--table-templates tables)
2348 (defun yas-insert-snippet (&optional no-condition)
2349 "Choose a snippet to expand, pop-up a list of choices according
2350 to `yas--prompt-function'.
2352 With prefix argument NO-CONDITION, bypass filtering of snippets
2355 (setq yas--condition-cache-timestamp (current-time))
2356 (let* ((yas-buffer-local-condition (or (and no-condition
2358 yas-buffer-local-condition))
2359 (templates (yas--all-templates (yas--get-snippet-tables)))
2360 (yas--current-template (and templates
2361 (or (and (rest templates) ;; more than one template for same key
2362 (yas--prompt-for-template templates))
2364 (where (if (region-active-p)
2365 (cons (region-beginning) (region-end))
2366 (cons (point) (point)))))
2367 (if yas--current-template
2368 (yas-expand-snippet (yas--template-content yas--current-template)
2371 (yas--template-expand-env yas--current-template))
2372 (yas--message 3 "No snippets can be inserted here!"))))
2374 (defun yas-visit-snippet-file ()
2375 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2377 Only success if selected snippet was loaded from a file. Put the
2378 visited file in `snippet-mode'."
2380 (let* ((yas-buffer-local-condition 'always)
2381 (templates (yas--all-templates (yas--get-snippet-tables)))
2382 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2383 (template (and templates
2384 (or (yas--prompt-for-template templates
2385 "Choose a snippet template to edit: ")
2389 (yas--visit-snippet-file-1 template)
2390 (message "No snippets tables active!"))))
2392 (defun yas--visit-snippet-file-1 (template)
2393 "Helper for `yas-visit-snippet-file'."
2394 (let ((file (yas--template-file template)))
2395 (cond ((and file (file-readable-p file))
2396 (find-file-other-window file)
2398 (set (make-local-variable 'yas--editing-template) template))
2400 (message "Original file %s no longer exists!" file))
2402 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2403 (let ((type 'snippet))
2404 (when (listp (yas--template-content template))
2405 (insert (format "# type: command\n"))
2406 (setq type 'command))
2407 (insert (format "# key: %s\n" (yas--template-key template)))
2408 (insert (format "# name: %s\n" (yas--template-name template)))
2409 (when (yas--template-keybinding template)
2410 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2411 (when (yas--template-expand-env template)
2412 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2413 (when (yas--template-condition template)
2414 (insert (format "# condition: %s\n" (yas--template-condition template))))
2416 (insert (if (eq type 'command)
2417 (pp-to-string (yas--template-content template))
2418 (yas--template-content template))))
2420 (set (make-local-variable 'yas--editing-template) template)))))
2422 (defun yas--guess-snippet-directories-1 (table)
2423 "Guess possible snippet subdirectories for TABLE."
2424 (cons (yas--table-name table)
2425 (mapcan #'(lambda (parent)
2426 (yas--guess-snippet-directories-1
2428 (yas--table-parents table))))
2430 (defun yas--guess-snippet-directories (&optional table)
2431 "Try to guess suitable directories based on the current active
2432 tables (or optional TABLE).
2434 Returns a list of elements (TABLE . DIRS) where TABLE is a
2435 `yas--table' object and DIRS is a list of all possible directories
2436 where snippets of table might exist."
2437 (let ((main-dir (replace-regexp-in-string
2439 (or (first (or (yas-snippet-dirs)
2440 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2441 (tables (or (and table
2443 (yas--get-snippet-tables))))
2444 ;; HACK! the snippet table created here is actually registered!
2446 (unless (or table (gethash major-mode yas--tables))
2447 (push (yas--table-get-create major-mode)
2450 (mapcar #'(lambda (table)
2452 (mapcar #'(lambda (subdir)
2453 (concat main-dir "/" subdir))
2454 (yas--guess-snippet-directories-1 table))))
2457 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2458 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2459 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2460 (let ((candidate (first (cdr table-and-dirs))))
2461 (unless (file-writable-p (file-name-directory candidate))
2462 (error (yas--format "%s is not writable." candidate)))
2463 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2465 (if (gethash (yas--table-mode (car table-and-dirs))
2469 (or main-table-string
2471 (yas--table-name (car table-and-dirs))))
2473 (make-directory candidate 'also-make-parents)
2474 ;; create the .yas-parents file here...
2477 (defun yas-new-snippet (&optional no-template)
2478 "Pops a new buffer for writing a snippet.
2480 Expands a snippet-writing snippet, unless the optional prefix arg
2481 NO-TEMPLATE is non-nil."
2483 (let ((guessed-directories (yas--guess-snippet-directories)))
2485 (switch-to-buffer "*new snippet*")
2487 (kill-all-local-variables)
2490 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2491 (yas--table-mode (car d)))
2492 guessed-directories))
2493 (if (and (not no-template) yas-new-snippet-default)
2494 (yas-expand-snippet yas-new-snippet-default))))
2496 (defun yas--compute-major-mode-and-parents (file)
2497 "Given FILE, find the nearest snippet directory for a given mode.
2499 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2500 representing one or more of the mode's parents.
2502 Note that MODE-SYM need not be the symbol of a real major mode,
2503 neither do the elements of PARENTS."
2504 (let* ((file-dir (and file
2505 (directory-file-name (or (some #'(lambda (special)
2506 (locate-dominating-file file special))
2510 (directory-file-name (file-name-directory file))))))
2511 (parents-file-name (concat file-dir "/.yas-parents"))
2512 (major-mode-name (and file-dir
2513 (file-name-nondirectory file-dir)))
2514 (major-mode-sym (or (and major-mode-name
2515 (intern major-mode-name))))
2516 (parents (when (file-readable-p parents-file-name)
2520 (insert-file-contents parents-file-name)
2521 (buffer-substring-no-properties (point-min)
2523 (when major-mode-sym
2524 (cons major-mode-sym (remove major-mode-sym parents)))))
2526 (defvar yas--editing-template nil
2527 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2529 (defvar yas--current-template nil
2530 "Holds the current template being expanded into a snippet.")
2532 (defvar yas--guessed-modes nil
2533 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2535 (defun yas--read-table ()
2536 "Ask user for a snippet table, help with some guessing."
2537 (let ((prompt (if (and (featurep 'ido)
2539 'ido-completing-read 'completing-read)))
2540 (unless yas--guessed-modes
2541 (set (make-local-variable 'yas--guessed-modes)
2542 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2544 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2545 (if yas--guessed-modes
2546 (first yas--guessed-modes)
2548 (mapcar #'symbol-name yas--guessed-modes)
2553 (if (first yas--guessed-modes)
2554 (symbol-name (first yas--guessed-modes)))))))
2556 (defun yas-load-snippet-buffer (table &optional interactive)
2557 "Parse and load current buffer's snippet definition into TABLE.
2559 TABLE is a symbol naming a passed to `yas--table-get-create'.
2561 When called interactively, prompt for the table name and
2562 whether (and where) to save the snippet, then quit the window."
2563 (interactive (list (yas--read-table) t))
2565 ;; We have `yas--editing-template', this buffer's content comes from a
2566 ;; template which is already loaded and neatly positioned,...
2568 (yas--editing-template
2569 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2570 (yas--template-table yas--editing-template)))
2571 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2572 ;; value from `yas--compute-major-mode-and-parents'
2575 (unless yas--guessed-modes
2576 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2577 (let* ((table (yas--table-get-create table)))
2578 (set (make-local-variable 'yas--editing-template)
2579 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2582 (when (and interactive
2584 ;; Only offer to save this if it looks like a library or new
2585 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2586 ;; which is not the first, or from an unwritable file)
2588 (not (yas--template-file yas--editing-template))
2589 (not (file-writable-p (yas--template-file yas--editing-template)))
2590 (and (listp yas-snippet-dirs)
2591 (second yas-snippet-dirs)
2592 (not (string-match (expand-file-name (first yas-snippet-dirs))
2593 (yas--template-file yas--editing-template)))))
2594 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2595 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2597 (yas--make-directory-maybe option))))
2599 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2600 (file-name-nondirectory (yas--template-file yas--editing-template)))
2601 (yas--template-name yas--editing-template))))
2602 (write-file (concat chosen "/"
2603 (read-from-minibuffer (format "File name to create in %s? " chosen)
2604 default-file-name)))
2605 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2607 (yas--message 3 "Snippet \"%s\" loaded for %s."
2608 (yas--template-name yas--editing-template)
2609 (yas--table-name (yas--template-table yas--editing-template)))
2610 (quit-window interactive)))
2612 (defun yas-tryout-snippet (&optional debug)
2613 "Test current buffer's snippet template in other buffer."
2615 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2616 (parsed (yas--parse-template))
2617 (test-mode (or (and (car major-mode-and-parent)
2618 (fboundp (car major-mode-and-parent))
2619 (car major-mode-and-parent))
2620 (first yas--guessed-modes)
2621 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2622 (yas--current-template
2625 (yas--populate-template (yas--make-blank-template)
2626 :table nil ;; no tables for ephemeral snippets
2628 :content (second parsed)
2629 :name (third parsed)
2630 :expand-env (sixth parsed)))))
2631 (cond (yas--current-template
2632 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2633 (kill-buffer (get-buffer-create buffer-name))
2634 (switch-to-buffer (get-buffer-create buffer-name))
2635 (setq buffer-undo-list nil)
2636 (condition-case nil (funcall test-mode) (error nil))
2638 (setq buffer-read-only nil)
2639 (yas-expand-snippet (yas--template-content yas--current-template)
2642 (yas--template-expand-env yas--current-template))
2644 (require 'yasnippet-debug nil t))
2645 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2647 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2649 (defun yas-active-keys ()
2650 "Return all active trigger keys for current buffer and point."
2652 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2655 (defun yas--template-fine-group (template)
2656 (car (last (or (yas--template-group template)
2657 (yas--template-perm-group template)))))
2659 (defun yas-describe-tables (&optional choose)
2660 "Display snippets for each table."
2662 (let* ((by-name-hash (and choose
2663 (y-or-n-p "Show by namehash? ")))
2664 (buffer (get-buffer-create "*YASnippet tables*"))
2665 (active-tables (yas--get-snippet-tables))
2666 (remain-tables (let ((all))
2667 (maphash #'(lambda (_k v)
2668 (unless (find v active-tables)
2672 (table-lists (list active-tables remain-tables))
2673 (original-buffer (current-buffer))
2675 (yas--condition-cache-timestamp (current-time)))
2676 (with-current-buffer buffer
2677 (setq buffer-read-only nil)
2679 (cond ((not by-name-hash)
2680 (insert "YASnippet tables: \n")
2681 (while (and table-lists
2683 (dolist (table (car table-lists))
2684 (yas--describe-pretty-table table original-buffer))
2685 (setq table-lists (cdr table-lists))
2687 (yas--create-snippet-xrefs)
2688 (display-buffer buffer)
2689 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2690 (yas--create-snippet-xrefs)
2694 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2695 (dolist (table (append active-tables remain-tables))
2696 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2698 (maphash #'(lambda (k _v)
2700 (yas--table-hash table))
2702 (insert (format " key %s maps snippets: %s\n" key
2704 (maphash #'(lambda (k _v)
2706 (gethash key (yas--table-hash table)))
2709 (setq buffer-read-only t))
2710 (display-buffer buffer)))
2712 (defun yas--describe-pretty-table (table &optional original-buffer)
2713 (insert (format "\nSnippet table `%s'"
2714 (yas--table-name table)))
2715 (if (yas--table-parents table)
2716 (insert (format " parents: %s\n"
2717 (mapcar #'yas--table-name
2718 (yas--table-parents table))))
2720 (insert (make-string 100 ?-) "\n")
2721 (insert "group state name key binding\n")
2722 (let ((groups-hash (make-hash-table :test #'equal)))
2723 (maphash #'(lambda (_k v)
2724 (let ((group (or (yas--template-fine-group v)
2726 (when (yas--template-name v)
2728 (cons v (gethash group groups-hash))
2730 (yas--table-uuidhash table))
2732 #'(lambda (group templates)
2733 (setq group (truncate-string-to-width group 25 0 ? "..."))
2734 (insert (make-string 100 ?-) "\n")
2735 (dolist (p templates)
2736 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2740 (setq group (make-string (length group) ? ))))
2741 (condition-string (let ((condition (yas--template-condition p)))
2744 (with-current-buffer original-buffer
2745 (if (yas--eval-condition condition)
2750 (insert condition-string " ")
2752 (if (string-match "\\.\\.\\.$" name)
2756 (insert (truncate-string-to-width (or (yas--template-key p) "")
2758 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2765 ;;; User convenience functions, for using in snippet definitions
2767 (defvar yas-modified-p nil
2768 "Non-nil if field has been modified by user or transformation.")
2770 (defvar yas-moving-away-p nil
2771 "Non-nil if user is about to exit field.")
2773 (defvar yas-text nil
2774 "Contains current field text.")
2776 (defun yas-substr (str pattern &optional subexp)
2777 "Search PATTERN in STR and return SUBEXPth match.
2779 If found, the content of subexp group SUBEXP (default 0) is
2780 returned, or else the original STR will be returned."
2781 (let ((grp (or subexp 0)))
2783 (if (string-match pattern str)
2784 (match-string-no-properties grp str)
2787 (defun yas-choose-value (&rest possibilities)
2788 "Prompt for a string in POSSIBILITIES and return it.
2790 The last element of POSSIBILITIES may be a list of strings."
2791 (unless (or yas-moving-away-p
2793 (setq possibilities (nreverse possibilities))
2794 (setq possibilities (if (listp (car possibilities))
2795 (append (reverse (car possibilities)) (rest possibilities))
2797 (some #'(lambda (fn)
2798 (funcall fn "Choose: " possibilities))
2799 yas-prompt-functions)))
2801 (defun yas-key-to-value (alist)
2802 (unless (or yas-moving-away-p
2804 (let ((key (read-key-sequence "")))
2806 (or (cdr (find key alist :key #'car :test #'string=))
2809 (defun yas-throw (text)
2810 "Throw a yas--exception with TEXT as the reason."
2811 (throw 'yas--exception (cons 'yas--exception text)))
2813 (defun yas-verify-value (possibilities)
2814 "Verify that the current field value is in POSSIBILITIES.
2816 Otherwise throw exception."
2817 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2818 (yas-throw (yas--format "Field only allows %s" possibilities))))
2820 (defun yas-field-value (number)
2821 "Get the string for field with NUMBER.
2823 Use this in primary and mirror transformations to tget."
2824 (let* ((snippet (car (yas--snippets-at-point)))
2826 (yas--snippet-find-field snippet number))))
2828 (yas--field-text-for-display field))))
2831 "Return `yas-text' if that exists and is non-empty, else nil."
2833 (not (string= "" yas-text)))
2836 (defun yas-selected-text ()
2837 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2838 (if (and yas-selected-text
2839 (not (string= "" yas-selected-text)))
2842 (defun yas--get-field-once (number &optional transform-fn)
2843 (unless yas-modified-p
2845 (funcall transform-fn (yas-field-value number))
2846 (yas-field-value number))))
2848 (defun yas-default-from-field (number)
2849 (unless yas-modified-p
2850 (yas-field-value number)))
2852 (defun yas-inside-string ()
2853 "Return non-nil if the point is inside a string according to font-lock."
2854 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2856 (defun yas-unimplemented (&optional missing-feature)
2857 (if yas--current-template
2858 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2861 (yas--visit-snippet-file-1 yas--current-template))
2862 (message "No implementation. Missing %s" (or missing-feature "something"))))
2865 ;;; Snippet expansion and field management
2867 (defvar yas--active-field-overlay nil
2868 "Overlays the currently active field.")
2870 (defvar yas--field-protection-overlays nil
2871 "Two overlays protect the current active field.")
2873 (defvar yas-selected-text nil
2874 "The selected region deleted on the last snippet expansion.")
2876 (defvar yas--start-column nil
2877 "The column where the snippet expansion started.")
2879 (make-variable-buffer-local 'yas--active-field-overlay)
2880 (make-variable-buffer-local 'yas--field-protection-overlays)
2881 (put 'yas--active-field-overlay 'permanent-local t)
2882 (put 'yas--field-protection-overlays 'permanent-local t)
2884 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2890 (id (yas--snippet-next-id) :read-only t)
2891 (control-overlay nil)
2893 ;; stacked expansion: the `previous-active-field' slot saves the
2894 ;; active field where the child expansion took place
2895 previous-active-field
2898 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2901 NUMBER is the field number.
2902 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2903 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2904 MIRRORS is a list of `yas--mirror's
2905 TRANSFORM is a lisp form.
2906 MODIFIED-P is a boolean set to true once user inputs text.
2907 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2918 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2921 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2922 TRANSFORM is a lisp form.
2923 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2924 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2925 DEPTH is a count of how many nested mirrors can affect this mirror"
2932 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2936 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2937 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2939 If there is no transform for ht field, return nil.
2941 If there is a transform but it returns nil, return the empty
2942 string iff EMPTY-ON-NIL-P is true."
2943 (let* ((yas-text (yas--field-text-for-display field))
2944 (yas-modified-p (yas--field-modified-p field))
2945 (yas-moving-away-p nil)
2946 (transform (if (yas--mirror-p field-or-mirror)
2947 (yas--mirror-transform field-or-mirror)
2948 (yas--field-transform field-or-mirror)))
2949 (start-point (if (yas--mirror-p field-or-mirror)
2950 (yas--mirror-start field-or-mirror)
2951 (yas--field-start field-or-mirror)))
2952 (transformed (and transform
2954 (goto-char start-point)
2955 (let ((ret (yas--eval-lisp transform)))
2956 (or ret (and empty-on-nil-p "")))))))
2959 (defsubst yas--replace-all (from to &optional text)
2960 "Replace all occurrences from FROM to TO.
2962 With optional string TEXT do it in that string."
2964 (replace-regexp-in-string (regexp-quote from) to text t t)
2965 (goto-char (point-min))
2966 (while (search-forward from nil t)
2967 (replace-match to t t text))))
2969 (defun yas--snippet-find-field (snippet number)
2970 (find-if #'(lambda (field)
2971 (eq number (yas--field-number field)))
2972 (yas--snippet-fields snippet)))
2974 (defun yas--snippet-sort-fields (snippet)
2975 "Sort the fields of SNIPPET in navigation order."
2976 (setf (yas--snippet-fields snippet)
2977 (sort (yas--snippet-fields snippet)
2978 #'yas--snippet-field-compare)))
2980 (defun yas--snippet-field-compare (field1 field2)
2981 "Compare FIELD1 and FIELD2.
2983 The field with a number is sorted first. If they both have a
2984 number, compare through the number. If neither have, compare
2985 through the field's start point"
2986 (let ((n1 (yas--field-number field1))
2987 (n2 (yas--field-number field2)))
2990 (or (zerop n2) (and (not (zerop n1))
2995 (< (yas--field-start field1)
2996 (yas--field-start field2))))))
2998 (defun yas--field-probably-deleted-p (snippet field)
2999 "Guess if SNIPPET's FIELD should be skipped."
3001 ;; field must be zero length
3003 (zerop (- (yas--field-start field) (yas--field-end field)))
3006 ;; 1) is a nested field and it's been modified
3008 (and (yas--field-parent-field field)
3009 (yas--field-modified-p field))
3010 ;; 2) ends just before the snippet end
3012 (and (eq field (car (last (yas--snippet-fields snippet))))
3013 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3014 ;; the field numbered 0, just before the exit marker, should
3017 (not (zerop (yas--field-number field)))))
3019 (defun yas--snippets-at-point (&optional all-snippets)
3020 "Return a sorted list of snippets at point.
3022 The most recently-inserted snippets are returned first."
3024 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3025 (overlay-get ov 'yas--snippet))
3027 (overlays-in (point-min) (point-max))
3028 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3030 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3032 (defun yas-next-field-or-maybe-expand ()
3033 "Try to expand a snippet at a key before point.
3035 Otherwise delegate to `yas-next-field'."
3037 (if yas-triggers-in-field
3038 (let ((yas-fallback-behavior 'return-nil)
3039 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3041 (unless (yas-expand-from-trigger-key active-field)
3045 (defun yas-next-field (&optional arg)
3046 "Navigate to the ARGth next field.
3048 If there's none, exit the snippet."
3052 (snippet (first (yas--snippets-at-point)))
3053 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3054 (live-fields (remove-if #'(lambda (field)
3055 (and (not (eq field active-field))
3056 (yas--field-probably-deleted-p snippet field)))
3057 (yas--snippet-fields snippet)))
3058 (active-field-pos (position active-field live-fields))
3059 (target-pos (and active-field-pos (+ arg active-field-pos)))
3060 (target-field (and target-pos (nth target-pos live-fields))))
3061 ;; First check if we're moving out of a field with a transform
3063 (when (and active-field
3064 (yas--field-transform active-field))
3065 (let* ((yas-moving-away-p t)
3066 (yas-text (yas--field-text-for-display active-field))
3067 (yas-modified-p (yas--field-modified-p active-field)))
3068 ;; primary field transform: exit call to field-transform
3069 (yas--eval-lisp (yas--field-transform active-field))))
3070 ;; Now actually move...
3071 (cond ((and target-pos (>= target-pos (length live-fields)))
3072 (yas-exit-snippet snippet))
3074 (yas--move-to-field snippet target-field))
3078 (defun yas--place-overlays (snippet field)
3079 "Correctly place overlays for SNIPPET's FIELD."
3080 (yas--make-move-field-protection-overlays snippet field)
3081 (yas--make-move-active-field-overlay snippet field))
3083 (defun yas--move-to-field (snippet field)
3084 "Update SNIPPET to move to field FIELD.
3086 Also create some protection overlays"
3087 (goto-char (yas--field-start field))
3088 (yas--place-overlays snippet field)
3089 (overlay-put yas--active-field-overlay 'yas--field field)
3090 (let ((number (yas--field-number field)))
3091 ;; check for the special ${0: ...} field
3092 (if (and number (zerop number))
3094 (set-mark (yas--field-end field))
3095 (setf (yas--snippet-force-exit snippet)
3096 (or (yas--field-transform field)
3098 ;; make this field active
3099 (setf (yas--snippet-active-field snippet) field)
3100 ;; primary field transform: first call to snippet transform
3101 (unless (yas--field-modified-p field)
3102 (if (yas--field-update-display field)
3103 (yas--update-mirrors snippet)
3104 (setf (yas--field-modified-p field) nil))))))
3106 (defun yas-prev-field ()
3107 "Navigate to prev field. If there's none, exit the snippet."
3109 (yas-next-field -1))
3111 (defun yas-abort-snippet (&optional snippet)
3113 (let ((snippet (or snippet
3114 (car (yas--snippets-at-point)))))
3116 (setf (yas--snippet-force-exit snippet) t))))
3118 (defun yas-exit-snippet (snippet)
3119 "Goto exit-marker of SNIPPET."
3120 (interactive (list (first (yas--snippets-at-point))))
3122 (setf (yas--snippet-force-exit snippet) t)
3123 (goto-char (if (yas--snippet-exit snippet)
3124 (yas--exit-marker (yas--snippet-exit snippet))
3125 (overlay-end (yas--snippet-control-overlay snippet))))))
3127 (defun yas-exit-all-snippets ()
3128 "Exit all snippets."
3130 (mapc #'(lambda (snippet)
3131 (yas-exit-snippet snippet)
3132 (yas--check-commit-snippet))
3133 (yas--snippets-at-point 'all-snippets)))
3136 ;;; Some low level snippet-routines:
3138 (defvar yas--inhibit-overlay-hooks nil
3139 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3141 (defmacro yas--inhibit-overlay-hooks (&rest body)
3142 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3143 (declare (indent 0))
3144 `(let ((yas--inhibit-overlay-hooks t))
3147 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3148 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3150 (defun yas--commit-snippet (snippet)
3151 "Commit SNIPPET, but leave point as it is.
3153 This renders the snippet as ordinary text."
3155 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3157 ;; Save the end of the moribund snippet in case we need to revive it
3158 ;; its original expansion.
3160 (when (and control-overlay
3161 (overlay-buffer control-overlay))
3162 (setq yas-snippet-beg (overlay-start control-overlay))
3163 (setq yas-snippet-end (overlay-end control-overlay))
3164 (delete-overlay control-overlay))
3166 (yas--inhibit-overlay-hooks
3167 (when yas--active-field-overlay
3168 (delete-overlay yas--active-field-overlay))
3169 (when yas--field-protection-overlays
3170 (mapc #'delete-overlay yas--field-protection-overlays)))
3172 ;; stacked expansion: if the original expansion took place from a
3173 ;; field, make sure we advance it here at least to
3174 ;; `yas-snippet-end'...
3176 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3177 (when (and yas-snippet-end previous-field)
3178 (yas--advance-end-maybe previous-field yas-snippet-end)))
3180 ;; Convert all markers to points,
3182 (yas--markers-to-points snippet)
3184 ;; Take care of snippet revival
3186 (if yas-snippet-revival
3187 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3189 ;; Dismember the snippet... this is useful if we get called
3190 ;; again from `yas--take-care-of-redo'....
3191 (setf (yas--snippet-fields snippet) nil)))
3193 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3195 (defun yas--safely-run-hooks (hook-var)
3196 (condition-case error
3197 (run-hooks hook-var)
3199 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3202 (defun yas--check-commit-snippet ()
3203 "Check if point exited the currently active field of the snippet.
3205 If so cleans up the whole snippet up."
3206 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3207 (snippets-left snippets)
3208 (snippet-exit-transform))
3209 (dolist (snippet snippets)
3210 (let ((active-field (yas--snippet-active-field snippet)))
3211 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3212 (cond ((or snippet-exit-transform
3213 (not (and active-field (yas--field-contains-point-p active-field))))
3214 (setq snippets-left (delete snippet snippets-left))
3215 (setf (yas--snippet-force-exit snippet) nil)
3216 (yas--commit-snippet snippet))
3218 (or (not yas--active-field-overlay)
3219 (not (overlay-buffer yas--active-field-overlay))))
3221 ;; stacked expansion: this case is mainly for recent
3222 ;; snippet exits that place us back int the field of
3226 (yas--move-to-field snippet active-field)
3227 (yas--update-mirrors snippet)))
3230 (unless (or (null snippets) snippets-left)
3231 (if snippet-exit-transform
3232 (yas--eval-lisp-no-saves snippet-exit-transform))
3233 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3235 ;; Apropos markers-to-points:
3237 ;; This was found useful for performance reasons, so that an
3238 ;; excessive number of live markers aren't kept around in the
3239 ;; `buffer-undo-list'. However, in `markers-to-points', the
3240 ;; set-to-nil markers can't simply be discarded and replaced with
3241 ;; fresh ones in `points-to-markers'. The original marker that was
3242 ;; just set to nil has to be reused.
3244 ;; This shouldn't bring horrible problems with undo/redo, but it
3247 (defun yas--markers-to-points (snippet)
3248 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3249 where POINT is the original position of the marker and MARKER is
3250 the original marker object with the position set to nil."
3251 (dolist (field (yas--snippet-fields snippet))
3252 (let ((start (marker-position (yas--field-start field)))
3253 (end (marker-position (yas--field-end field))))
3254 (set-marker (yas--field-start field) nil)
3255 (set-marker (yas--field-end field) nil)
3256 (setf (yas--field-start field) (cons start (yas--field-start field)))
3257 (setf (yas--field-end field) (cons end (yas--field-end field))))
3258 (dolist (mirror (yas--field-mirrors field))
3259 (let ((start (marker-position (yas--mirror-start mirror)))
3260 (end (marker-position (yas--mirror-end mirror))))
3261 (set-marker (yas--mirror-start mirror) nil)
3262 (set-marker (yas--mirror-end mirror) nil)
3263 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3264 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3265 (let ((snippet-exit (yas--snippet-exit snippet)))
3267 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3268 (set-marker (yas--exit-marker snippet-exit) nil)
3269 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3271 (defun yas--points-to-markers (snippet)
3272 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3274 This is done by setting MARKER to POINT with `set-marker'."
3275 (dolist (field (yas--snippet-fields snippet))
3276 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3277 (car (yas--field-start field))))
3278 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3279 (car (yas--field-end field))))
3280 (dolist (mirror (yas--field-mirrors field))
3281 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3282 (car (yas--mirror-start mirror))))
3283 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3284 (car (yas--mirror-end mirror))))))
3285 (let ((snippet-exit (yas--snippet-exit snippet)))
3287 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3288 (car (yas--exit-marker snippet-exit)))))))
3290 (defun yas--field-contains-point-p (field &optional point)
3291 (let ((point (or point
3293 (and (>= point (yas--field-start field))
3294 (<= point (yas--field-end field)))))
3296 (defun yas--field-text-for-display (field)
3297 "Return the propertized display text for field FIELD."
3298 (buffer-substring (yas--field-start field) (yas--field-end field)))
3300 (defun yas--undo-in-progress ()
3301 "True if some kind of undo is in progress."
3302 (or undo-in-progress
3303 (eq this-command 'undo)
3304 (eq this-command 'redo)))
3306 (defun yas--make-control-overlay (snippet start end)
3307 "Create the control overlay that surrounds the snippet and
3309 (let ((overlay (make-overlay start
3314 (overlay-put overlay 'keymap yas-keymap)
3315 (overlay-put overlay 'priority 100)
3316 (overlay-put overlay 'yas--snippet snippet)
3319 (defun yas-skip-and-clear-or-delete-char (&optional field)
3320 "Clears unmodified field if at field start, skips to next tab.
3322 Otherwise deletes a character normally by calling `delete-char'."
3324 (let ((field (or field
3325 (and yas--active-field-overlay
3326 (overlay-buffer yas--active-field-overlay)
3327 (overlay-get yas--active-field-overlay 'yas--field)))))
3329 (not (yas--field-modified-p field))
3330 (eq (point) (marker-position (yas--field-start field))))
3331 (yas--skip-and-clear field)
3334 (call-interactively 'delete-char)))))
3336 (defun yas--skip-and-clear (field)
3337 "Deletes the region of FIELD and sets it's modified state to t."
3338 ;; Just before skipping-and-clearing the field, mark its children
3339 ;; fields as modified, too. If the children have mirrors-in-fields
3340 ;; this prevents them from updating erroneously (we're skipping and
3343 (yas--mark-this-and-children-modified field)
3344 (delete-region (yas--field-start field) (yas--field-end field)))
3346 (defun yas--mark-this-and-children-modified (field)
3347 (setf (yas--field-modified-p field) t)
3348 (let ((fom (yas--field-next field)))
3350 (yas--fom-parent-field fom))
3351 (when (and (eq (yas--fom-parent-field fom) field)
3353 (yas--mark-this-and-children-modified fom))
3354 (setq fom (yas--fom-next fom)))))
3356 (defun yas--make-move-active-field-overlay (snippet field)
3357 "Place the active field overlay in SNIPPET's FIELD.
3359 Move the overlay, or create it if it does not exit."
3360 (if (and yas--active-field-overlay
3361 (overlay-buffer yas--active-field-overlay))
3362 (move-overlay yas--active-field-overlay
3363 (yas--field-start field)
3364 (yas--field-end field))
3365 (setq yas--active-field-overlay
3366 (make-overlay (yas--field-start field)
3367 (yas--field-end field)
3369 (overlay-put yas--active-field-overlay 'priority 100)
3370 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3371 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3372 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3373 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3374 '(yas--on-field-overlay-modification))
3375 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3376 '(yas--on-field-overlay-modification))))
3378 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3379 "Clears the field and updates mirrors, conditionally.
3381 Only clears the field if it hasn't been modified and it point it
3382 at field start. This hook doesn't do anything if an undo is in
3384 (unless (or yas--inhibit-overlay-hooks
3385 (yas--undo-in-progress))
3386 (let* ((field (overlay-get overlay 'yas--field))
3387 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3389 (yas--advance-end-maybe field (overlay-end overlay))
3391 (yas--field-update-display field))
3392 (yas--update-mirrors snippet))
3394 (when (and (not after?)
3395 (not (yas--field-modified-p field))
3396 (eq (point) (if (markerp (yas--field-start field))
3397 (marker-position (yas--field-start field))
3398 (yas--field-start field))))
3399 (yas--skip-and-clear field))
3400 (setf (yas--field-modified-p field) t))))))
3402 ;;; Apropos protection overlays:
3404 ;; These exist for nasty users who will try to delete parts of the
3405 ;; snippet outside the active field. Actual protection happens in
3406 ;; `yas--on-protection-overlay-modification'.
3408 ;; Currently this signals an error which inhibits the command. For
3409 ;; commands that move point (like `kill-line'), point is restored in
3410 ;; the `yas--post-command-handler' using a global
3411 ;; `yas--protection-violation' variable.
3413 ;; Alternatively, I've experimented with an implementation that
3414 ;; commits the snippet before actually calling `this-command'
3415 ;; interactively, and then signals an error, which is ignored. but
3416 ;; blocks all other million modification hooks. This presented some
3417 ;; problems with stacked expansion.
3419 (defun yas--make-move-field-protection-overlays (snippet field)
3420 "Place protection overlays surrounding SNIPPET's FIELD.
3422 Move the overlays, or create them if they do not exit."
3423 (let ((start (yas--field-start field))
3424 (end (yas--field-end field)))
3425 ;; First check if the (1+ end) is contained in the buffer,
3426 ;; otherwise we'll have to do a bit of cheating and silently
3427 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3428 ;; when using stacked expansion
3430 (when (< (buffer-size) end)
3432 (yas--inhibit-overlay-hooks
3433 (goto-char (point-max))
3435 ;; go on to normal overlay creation/moving
3437 (cond ((and yas--field-protection-overlays
3438 (every #'overlay-buffer yas--field-protection-overlays))
3439 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3440 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3442 (setq yas--field-protection-overlays
3443 (list (make-overlay (1- start) start nil t nil)
3444 (make-overlay end (1+ end) nil t nil)))
3445 (dolist (ov yas--field-protection-overlays)
3446 (overlay-put ov 'face 'yas--field-debug-face)
3447 (overlay-put ov 'yas--snippet snippet)
3448 ;; (overlay-put ov 'evaporate t)
3449 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3451 (defvar yas--protection-violation nil
3452 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3454 Functions in the `post-command-hook', for example
3455 `yas--post-command-handler' can check it and reset its value to
3456 nil. The variables value is the point where the violation
3459 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3460 "Signals a snippet violation, then issues error.
3462 The error should be ignored in `debug-ignored-errors'"
3463 (unless yas--inhibit-overlay-hooks
3464 (cond ((not (or after?
3465 (yas--undo-in-progress)))
3466 (setq yas--protection-violation (point))
3467 (error "Exit the snippet first!")))))
3469 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3472 ;;; Snippet expansion and "stacked" expansion:
3474 ;; Stacked expansion is when you try to expand a snippet when already
3475 ;; inside a snippet expansion.
3477 ;; The parent snippet does not run its fields modification hooks
3478 ;; (`yas--on-field-overlay-modification' and
3479 ;; `yas--on-protection-overlay-modification') while the child snippet
3480 ;; is active. This means, among other things, that the mirrors of the
3481 ;; parent snippet are not updated, this only happening when one exits
3482 ;; the child snippet.
3484 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3485 ;; bits of code in `yas-expand-snippet' and
3486 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3489 ;; This was thought to be safer in an undo/redo perspective, but
3490 ;; maybe the correct implementation is to make the globals
3491 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3492 ;; snippet-local and be active even while the child snippet is
3493 ;; running. This would mean a lot of overlay modification hooks
3494 ;; running, but if managed correctly (including overlay priorities)
3495 ;; they should account for all situations...
3497 (defun yas-expand-snippet (content &optional start end expand-env)
3498 "Expand snippet CONTENT at current point.
3500 Text between START and END will be deleted before inserting
3501 template. EXPAND-ENV is are let-style variable to value bindings
3502 considered when expanding the snippet."
3503 (run-hooks 'yas-before-expand-snippet-hook)
3506 (let* ((yas-selected-text (or yas-selected-text
3507 (and (region-active-p)
3508 (buffer-substring-no-properties (region-beginning)
3511 (and (region-active-p)
3515 (and (region-active-p)
3518 (to-delete (and start
3520 (buffer-substring-no-properties start end)))
3523 (setq yas--indent-original-column (current-column))
3524 ;; Delete the region to delete, this *does* get undo-recorded.
3526 (when (and to-delete
3528 (delete-region start end))
3530 (cond ((listp content)
3531 ;; x) This is a snippet-command
3533 (yas--eval-lisp-no-saves content))
3535 ;; x) This is a snippet-snippet :-)
3537 ;; Narrow the region down to the content, shoosh the
3538 ;; `buffer-undo-list', and create the snippet, the new
3539 ;; snippet updates its mirrors once, so we are left with
3540 ;; some plain text. The undo action for deleting this
3541 ;; plain text will get recorded at the end.
3543 ;; stacked expansion: also shoosh the overlay modification hooks
3545 (narrow-to-region start start)
3546 (let ((buffer-undo-list t))
3547 ;; snippet creation might evaluate users elisp, which
3548 ;; might generate errors, so we have to be ready to catch
3549 ;; them mostly to make the undo information
3551 (setq yas--start-column (save-restriction (widen) (current-column)))
3552 (yas--inhibit-overlay-hooks
3555 (eval `(let* ,expand-env
3557 (yas--snippet-create (point-min))))
3559 (yas--snippet-create (point-min)))))))
3561 ;; stacked-expansion: This checks for stacked expansion, save the
3562 ;; `yas--previous-active-field' and advance its boundary.
3564 (let ((existing-field (and yas--active-field-overlay
3565 (overlay-buffer yas--active-field-overlay)
3566 (overlay-get yas--active-field-overlay 'yas--field))))
3567 (when existing-field
3568 (setf (yas--snippet-previous-active-field snippet) existing-field)
3569 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3571 ;; Exit the snippet immediately if no fields
3573 (unless (yas--snippet-fields snippet)
3574 (yas-exit-snippet snippet))
3576 ;; Push two undo actions: the deletion of the inserted contents of
3577 ;; the new snippet (without the "key") followed by an apply of
3578 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3580 ;; A small exception, if `yas-also-auto-indent-first-line'
3581 ;; is t and `yas--indent' decides to indent the line to a
3582 ;; point before the actual expansion point, undo would be
3583 ;; messed up. We call the early point "newstart"". case,
3584 ;; and attempt to fix undo.
3586 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3587 (end (overlay-end (yas--snippet-control-overlay snippet))))
3588 (when (< newstart start)
3589 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3590 (push (cons newstart end) buffer-undo-list)
3591 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3593 ;; Now, schedule a move to the first field
3595 (let ((first-field (car (yas--snippet-fields snippet))))
3597 (sit-for 0) ;; fix issue 125
3598 (yas--move-to-field snippet first-field)))
3599 (yas--message 3 "snippet expanded.")
3602 (defun yas--take-care-of-redo (_beg _end snippet)
3603 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3605 Meant to exit in the `buffer-undo-list'."
3606 ;; slightly optimize: this action is only needed for snippets with
3607 ;; at least one field
3608 (when (yas--snippet-fields snippet)
3609 (yas--commit-snippet snippet)))
3611 (defun yas--snippet-revive (beg end snippet)
3612 "Revives SNIPPET and creates a control overlay from BEG to END.
3614 BEG and END are, we hope, the original snippets boundaries.
3615 All the markers/points exiting existing inside SNIPPET should point
3616 to their correct locations *at the time the snippet is revived*.
3618 After revival, push the `yas--take-care-of-redo' in the
3620 ;; Reconvert all the points to markers
3622 (yas--points-to-markers snippet)
3623 ;; When at least one editable field existed in the zombie snippet,
3624 ;; try to revive the whole thing...
3626 (let ((target-field (or (yas--snippet-active-field snippet)
3627 (car (yas--snippet-fields snippet)))))
3629 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3630 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3632 (yas--move-to-field snippet target-field)
3634 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3635 buffer-undo-list))))
3637 (defun yas--snippet-create (begin)
3638 "Create a snippet from a template inserted at BEGIN.
3640 Returns the newly created snippet."
3641 (let ((snippet (yas--make-snippet)))
3643 (yas--snippet-parse-create snippet)
3645 ;; Sort and link each field
3646 (yas--snippet-sort-fields snippet)
3648 ;; Create keymap overlay for snippet
3649 (setf (yas--snippet-control-overlay snippet)
3650 (yas--make-control-overlay snippet (point-min) (point-max)))
3653 (goto-char (point-max))
3658 ;;; Apropos adjacencies and "fom's":
3660 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3661 ;; recently expanded snippet, we might actually have many fields,
3662 ;; mirrors (and the snippet exit) in the very same position in the
3663 ;; buffer. Therefore we need to single-link the
3664 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3665 ;; according to their original positions in the buffer.
3667 ;; Then we have operation `yas--advance-end-maybe' and
3668 ;; `yas--advance-start-maybe', which conditionally push the starts and
3669 ;; ends of these foms down the chain.
3671 ;; This allows for like the printf with the magic ",":
3673 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3674 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3676 (defun yas--fom-start (fom)
3677 (cond ((yas--field-p fom)
3678 (yas--field-start fom))
3679 ((yas--mirror-p fom)
3680 (yas--mirror-start fom))
3682 (yas--exit-marker fom))))
3684 (defun yas--fom-end (fom)
3685 (cond ((yas--field-p fom)
3686 (yas--field-end fom))
3687 ((yas--mirror-p fom)
3688 (yas--mirror-end fom))
3690 (yas--exit-marker fom))))
3692 (defun yas--fom-next (fom)
3693 (cond ((yas--field-p fom)
3694 (yas--field-next fom))
3695 ((yas--mirror-p fom)
3696 (yas--mirror-next fom))
3698 (yas--exit-next fom))))
3700 (defun yas--fom-parent-field (fom)
3701 (cond ((yas--field-p fom)
3702 (yas--field-parent-field fom))
3703 ((yas--mirror-p fom)
3704 (yas--mirror-parent-field fom))
3708 (defun yas--calculate-adjacencies (snippet)
3709 "Calculate adjacencies for fields or mirrors of SNIPPET.
3711 This is according to their relative positions in the buffer, and
3712 has to be called before the $-constructs are deleted."
3713 (let* ((fom-set-next-fom
3714 (lambda (fom nextfom)
3715 (cond ((yas--field-p fom)
3716 (setf (yas--field-next fom) nextfom))
3717 ((yas--mirror-p fom)
3718 (setf (yas--mirror-next fom) nextfom))
3720 (setf (yas--exit-next fom) nextfom)))))
3723 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3724 (yas--mirror-p fom2)
3725 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3726 (link-foms fom-set-next-fom))
3727 ;; make some yas--field, yas--mirror and yas--exit soup
3729 (when (yas--snippet-exit snippet)
3730 (push (yas--snippet-exit snippet) soup))
3731 (dolist (field (yas--snippet-fields snippet))
3733 (dolist (mirror (yas--field-mirrors field))
3734 (push mirror soup)))
3736 (sort soup compare-fom-begs))
3738 (reduce link-foms soup)))))
3740 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3741 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3743 Use the tightest containing field if more than one field contains
3744 the mirror. Intended to be called *before* the dollar-regions are
3746 (let ((min (point-min))
3748 (dolist (field (yas--snippet-fields snippet))
3749 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3750 (<= (yas--mirror-end mirror) (yas--field-end field))
3751 (< min (yas--field-start field))
3752 (< (yas--field-end field) max))
3753 (setq min (yas--field-start field)
3754 max (yas--field-end field))
3755 (setf (yas--mirror-parent-field mirror) field)))))
3757 (defun yas--advance-end-maybe (fom newend)
3758 "Maybe advance FOM's end to NEWEND if it needs it.
3762 * call `yas--advance-start-maybe' on FOM's next fom.
3764 * in case FOM is field call `yas--advance-end-maybe' on its parent
3767 Also, if FOM is an exit-marker, always call
3768 `yas--advance-start-maybe' on its next fom. This is because
3769 exit-marker have identical start and end markers."
3770 (cond ((and fom (< (yas--fom-end fom) newend))
3771 (set-marker (yas--fom-end fom) newend)
3772 (yas--advance-start-maybe (yas--fom-next fom) newend)
3773 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3775 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3777 (defun yas--advance-start-maybe (fom newstart)
3778 "Maybe advance FOM's start to NEWSTART if it needs it.
3780 If it does, also call `yas--advance-end-maybe' on FOM."
3781 (when (and fom (< (yas--fom-start fom) newstart))
3782 (set-marker (yas--fom-start fom) newstart)
3783 (yas--advance-end-maybe fom newstart)))
3785 (defun yas--advance-end-of-parents-maybe (field newend)
3786 "Like `yas--advance-end-maybe' but for parent fields.
3788 Only works for fields and doesn't care about the start of the
3789 next FOM. Works its way up recursively for parents of parents."
3791 (< (yas--field-end field) newend))
3792 (set-marker (yas--field-end field) newend)
3793 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3795 (defvar yas--dollar-regions nil
3796 "When expanding the snippet the \"parse-create\" functions add
3797 cons cells to this var.")
3799 (defvar yas--backquote-markers-and-strings nil
3800 "List of (MARKER . STRING) marking where the values from
3801 backquoted Lisp expressions should be inserted at the end of
3804 (defun yas--snippet-parse-create (snippet)
3805 "Parse a recently inserted snippet template, creating all
3806 necessary fields, mirrors and exit points.
3808 Meant to be called in a narrowed buffer, does various passes"
3809 (let ((parse-start (point)))
3810 ;; Reset the yas--dollar-regions
3812 (setq yas--dollar-regions nil)
3813 ;; protect just the backquotes
3815 (yas--protect-escapes nil '(?`))
3816 ;; replace all backquoted expressions
3818 (goto-char parse-start)
3819 (yas--save-backquotes)
3820 ;; protect escaped characters
3822 (yas--protect-escapes)
3823 ;; parse fields with {}
3825 (goto-char parse-start)
3826 (yas--field-parse-create snippet)
3827 ;; parse simple mirrors and fields
3829 (goto-char parse-start)
3830 (yas--simple-mirror-parse-create snippet)
3831 ;; parse mirror transforms
3833 (goto-char parse-start)
3834 (yas--transform-mirror-parse-create snippet)
3835 ;; calculate adjacencies of fields and mirrors
3837 (yas--calculate-adjacencies snippet)
3838 ;; Delete $-constructs
3840 (yas--delete-regions yas--dollar-regions)
3841 ;; restore backquoted expression values
3843 (yas--restore-backquotes)
3846 (goto-char parse-start)
3847 (yas--restore-escapes)
3848 ;; update mirrors for the first time
3850 (yas--update-mirrors snippet)
3851 ;; indent the best we can
3853 (goto-char parse-start)
3854 (yas--indent snippet)))
3856 (defun yas--indent-according-to-mode (snippet-markers)
3857 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3858 ;;; Apropos indenting problems....
3860 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3861 ;; is available. Some implementations of these functions delete text
3862 ;; before they insert. If there happens to be a marker just after
3863 ;; the text being deleted, the insertion actually happens after the
3864 ;; marker, which misplaces it.
3866 ;; This would also happen if we had used overlays with the
3867 ;; `front-advance' property set to nil.
3869 ;; This is why I have these `trouble-markers', they are the ones at
3870 ;; they are the ones at the first non-whitespace char at the line
3871 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3872 ;; we should be at the correct to restore them to. All other
3873 ;; non-trouble-markers have been *pushed* and don't need special
3876 (goto-char (yas--real-line-beginning))
3877 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3883 (indent-according-to-mode)
3884 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3886 (mapc #'(lambda (marker)
3887 (set-marker marker (point)))
3890 (defvar yas--indent-original-column nil)
3891 (defun yas--indent (snippet)
3892 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3893 ;; Look for those $>
3895 (while (re-search-forward "$>" nil t)
3896 (delete-region (match-beginning 0) (match-end 0))
3897 (when (not (eq yas-indent-line 'auto))
3898 (yas--indent-according-to-mode snippet-markers))))
3899 ;; Now do stuff for 'fixed and 'auto
3901 (cond ((eq yas-indent-line 'fixed)
3902 (while (and (zerop (forward-line))
3903 (zerop (current-column)))
3904 (indent-to-column yas--indent-original-column)))
3905 ((eq yas-indent-line 'auto)
3906 (let ((end (set-marker (make-marker) (point-max)))
3907 (indent-first-line-p yas-also-auto-indent-first-line))
3908 (while (and (zerop (if indent-first-line-p
3911 (setq indent-first-line-p nil))
3915 (yas--indent-according-to-mode snippet-markers))))
3919 (defun yas--collect-snippet-markers (snippet)
3920 "Make a list of all the markers used by SNIPPET."
3922 (dolist (field (yas--snippet-fields snippet))
3923 (push (yas--field-start field) markers)
3924 (push (yas--field-end field) markers)
3925 (dolist (mirror (yas--field-mirrors field))
3926 (push (yas--mirror-start mirror) markers)
3927 (push (yas--mirror-end mirror) markers)))
3928 (let ((snippet-exit (yas--snippet-exit snippet)))
3929 (when (and snippet-exit
3930 (marker-buffer (yas--exit-marker snippet-exit)))
3931 (push (yas--exit-marker snippet-exit) markers)))
3934 (defun yas--real-line-beginning ()
3935 (let ((c (char-after (line-beginning-position)))
3936 (n (line-beginning-position)))
3937 (while (or (eql c ?\ )
3940 (setq c (char-after n)))
3943 (defun yas--escape-string (escaped)
3944 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3946 (defun yas--protect-escapes (&optional text escaped)
3947 "Protect all escaped characters with their numeric ASCII value.
3949 With optional string TEXT do it in string instead of buffer."
3950 (let ((changed-text text)
3951 (text-provided-p text))
3952 (mapc #'(lambda (escaped)
3954 (yas--replace-all (concat "\\" (char-to-string escaped))
3955 (yas--escape-string escaped)
3956 (when text-provided-p changed-text))))
3957 (or escaped yas--escaped-characters))
3960 (defun yas--restore-escapes (&optional text escaped)
3961 "Restore all escaped characters from their numeric ASCII value.
3963 With optional string TEXT do it in string instead of the buffer."
3964 (let ((changed-text text)
3965 (text-provided-p text))
3966 (mapc #'(lambda (escaped)
3968 (yas--replace-all (yas--escape-string escaped)
3969 (char-to-string escaped)
3970 (when text-provided-p changed-text))))
3971 (or escaped yas--escaped-characters))
3974 (defun yas--save-backquotes ()
3975 "Save all the \"`(lisp-expression)`\"-style expressions
3976 with their evaluated value into `yas--backquote-markers-and-strings'."
3977 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3978 (let ((current-string (match-string-no-properties 1)) transformed)
3979 (delete-region (match-beginning 0) (match-end 0))
3980 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3981 (goto-char (match-beginning 0))
3983 (let ((marker (make-marker)))
3984 (insert "Y") ;; quite horrendous, I love it :)
3985 (set-marker marker (point))
3987 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3989 (defun yas--restore-backquotes ()
3990 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3991 (while yas--backquote-markers-and-strings
3992 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3993 (marker (car marker-and-string))
3994 (string (cdr marker-and-string)))
4000 (set-marker marker nil)))))
4002 (defun yas--scan-sexps (from count)
4004 (with-syntax-table (standard-syntax-table)
4005 (scan-sexps from count))
4009 (defun yas--make-marker (pos)
4010 "Create a marker at POS with nil `marker-insertion-type'."
4011 (let ((marker (set-marker (make-marker) pos)))
4012 (set-marker-insertion-type marker nil)
4015 (defun yas--field-parse-create (snippet &optional parent-field)
4016 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4018 The following count as a field:
4020 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4022 * \"${n: text$(expression)}, the same with a Lisp expression;
4023 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4025 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4027 When multiple expressions are found, only the last one counts."
4030 (while (re-search-forward yas--field-regexp nil t)
4031 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4032 (number (and (match-string-no-properties 1)
4033 (string-to-number (match-string-no-properties 1))))
4034 (brand-new-field (and real-match-end-0
4035 ;; break if on "$(" immediately
4036 ;; after the ":", this will be
4037 ;; caught as a mirror with
4039 (not (save-match-data
4040 (eq (string-match "$[ \t\n]*("
4041 (match-string-no-properties 2)) 0)))
4042 ;; allow ${0: some exit text}
4043 ;; (not (and number (zerop number)))
4044 (yas--make-field number
4045 (yas--make-marker (match-beginning 2))
4046 (yas--make-marker (1- real-match-end-0))
4048 (when brand-new-field
4049 (goto-char real-match-end-0)
4050 (push (cons (1- real-match-end-0) real-match-end-0)
4051 yas--dollar-regions)
4052 (push (cons (match-beginning 0) (match-beginning 2))
4053 yas--dollar-regions)
4054 (push brand-new-field (yas--snippet-fields snippet))
4057 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4058 (goto-char (point-min))
4059 (yas--field-parse-create snippet brand-new-field)))))))
4060 ;; if we entered from a parent field, now search for the
4061 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4062 ;; primary field transformations
4066 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4067 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4068 ;; commit the primary field transformation if:
4070 ;; 1. we don't find it in yas--dollar-regions (a subnested
4071 ;; field) might have already caught it.
4073 ;; 2. we really make sure we have either two '$' or some
4074 ;; text and a '$' after the colon ':'. This is a FIXME: work
4075 ;; my regular expressions and end these ugly hacks.
4077 (when (and real-match-end-1
4078 (not (member (cons (match-beginning 0)
4080 yas--dollar-regions))
4082 (char-before (1- (match-beginning 1))))))
4083 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4085 (setf (yas--field-transform parent-field)
4086 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4087 (push (cons (match-beginning 0) real-match-end-1)
4088 yas--dollar-regions)))))))
4090 (defun yas--transform-mirror-parse-create (snippet)
4091 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4092 (while (re-search-forward yas--transform-mirror-regexp nil t)
4093 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4094 (number (string-to-number (match-string-no-properties 1)))
4096 (not (zerop number))
4097 (yas--snippet-find-field snippet number)))
4099 (and real-match-end-0
4101 (yas--make-mirror (yas--make-marker (match-beginning 0))
4102 (yas--make-marker (match-beginning 0))
4104 (yas--restore-escapes
4105 (buffer-substring-no-properties (match-beginning 2)
4106 (1- real-match-end-0))))))))
4107 (when brand-new-mirror
4108 (push brand-new-mirror
4109 (yas--field-mirrors field))
4110 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4111 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4113 (defun yas--simple-mirror-parse-create (snippet)
4114 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4115 (while (re-search-forward yas--simple-mirror-regexp nil t)
4116 (let ((number (string-to-number (match-string-no-properties 1))))
4117 (cond ((zerop number)
4119 (setf (yas--snippet-exit snippet)
4120 (yas--make-exit (yas--make-marker (match-end 0))))
4122 (goto-char (match-beginning 0))
4123 (when yas-wrap-around-region
4124 (cond (yas-selected-text
4125 (insert yas-selected-text))
4126 ((and (eq yas-wrap-around-region 'cua)
4129 (insert (prog1 (get-register ?0)
4130 (set-register ?0 nil))))))
4131 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4132 yas--dollar-regions)))
4134 (let ((field (yas--snippet-find-field snippet number)))
4136 (let ((brand-new-mirror (yas--make-mirror
4137 (yas--make-marker (match-beginning 0))
4138 (yas--make-marker (match-beginning 0))
4140 (push brand-new-mirror
4141 (yas--field-mirrors field))
4142 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4143 (push (yas--make-field number
4144 (yas--make-marker (match-beginning 0))
4145 (yas--make-marker (match-beginning 0))
4147 (yas--snippet-fields snippet))))
4148 (push (cons (match-beginning 0) (match-end 0))
4149 yas--dollar-regions))))))
4151 (defun yas--delete-regions (regions)
4152 "Sort disjuct REGIONS by start point, then delete from the back."
4153 (mapc #'(lambda (reg)
4154 (delete-region (car reg) (cdr reg)))
4157 (>= (car r1) (car r2))))))
4159 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4160 (let* ((parent (yas--mirror-parent-field mirror))
4161 (parents-mirrors (and parent
4162 (yas--field-mirrors parent))))
4163 (or (yas--mirror-depth mirror)
4164 (setf (yas--mirror-depth mirror)
4165 (cond ((memq mirror traversed)
4167 ((and parent parents-mirrors)
4169 (mapcar #'(lambda (m)
4170 (yas--calculate-mirror-depth m
4179 (defun yas--update-mirrors (snippet)
4180 "Update all the mirrors of SNIPPET."
4182 (dolist (field-and-mirror (sort
4183 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4184 ;; where F is the field that M is mirroring
4186 (mapcan #'(lambda (field)
4187 (mapcar #'(lambda (mirror)
4188 (cons field mirror))
4189 (yas--field-mirrors field)))
4190 (yas--snippet-fields snippet))
4191 ;; then sort this list so that entries with mirrors with parent
4192 ;; fields appear before. This was important for fixing #290, and
4193 ;; luckily also handles the case where a mirror in a field causes
4194 ;; another mirror to need reupdating
4196 #'(lambda (field-and-mirror1 field-and-mirror2)
4197 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4198 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4199 (let* ((field (car field-and-mirror))
4200 (mirror (cdr field-and-mirror))
4201 (parent-field (yas--mirror-parent-field mirror)))
4202 ;; before updating a mirror with a parent-field, maybe advance
4206 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4207 ;; update this mirror
4209 (yas--mirror-update-display mirror field)
4210 ;; `yas--place-overlays' is needed if the active field and
4211 ;; protected overlays have been changed because of insertions
4212 ;; in `yas--mirror-update-display'
4214 (when (eq field (yas--snippet-active-field snippet))
4215 (yas--place-overlays snippet field))))))
4217 (defun yas--mirror-update-display (mirror field)
4218 "Update MIRROR according to FIELD (and mirror transform)."
4220 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4221 (reflection (and (not (and mirror-parent-field
4222 (yas--field-modified-p mirror-parent-field)))
4223 (or (yas--apply-transform mirror field 'empty-on-nil)
4224 (yas--field-text-for-display field)))))
4225 (when (and reflection
4226 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4227 (yas--mirror-end mirror)))))
4228 (goto-char (yas--mirror-start mirror))
4229 (yas--inhibit-overlay-hooks
4230 (insert reflection))
4231 (if (> (yas--mirror-end mirror) (point))
4232 (delete-region (point) (yas--mirror-end mirror))
4233 (set-marker (yas--mirror-end mirror) (point))
4234 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4235 ;; super-special advance
4236 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4238 (defun yas--field-update-display (field)
4239 "Much like `yas--mirror-update-display', but for fields."
4240 (when (yas--field-transform field)
4241 (let ((transformed (and (not (eq (yas--field-number field) 0))
4242 (yas--apply-transform field field))))
4243 (when (and transformed
4244 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4245 (yas--field-end field)))))
4246 (setf (yas--field-modified-p field) t)
4247 (goto-char (yas--field-start field))
4248 (yas--inhibit-overlay-hooks
4249 (insert transformed)
4250 (if (> (yas--field-end field) (point))
4251 (delete-region (point) (yas--field-end field))
4252 (set-marker (yas--field-end field) (point))
4253 (yas--advance-start-maybe (yas--field-next field) (point)))
4257 ;;; Post-command hook:
4259 (defun yas--post-command-handler ()
4260 "Handles various yasnippet conditions after each command."
4261 (cond (yas--protection-violation
4262 (goto-char yas--protection-violation)
4263 (setq yas--protection-violation nil))
4264 ((eq 'undo this-command)
4266 ;; After undo revival the correct field is sometimes not
4267 ;; restored correctly, this condition handles that
4269 (let* ((snippet (car (yas--snippets-at-point)))
4270 (target-field (and snippet
4271 (find-if-not #'(lambda (field)
4272 (yas--field-probably-deleted-p snippet field))
4274 (cons (yas--snippet-active-field snippet)
4275 (yas--snippet-fields snippet)))))))
4277 (yas--move-to-field snippet target-field))))
4278 ((not (yas--undo-in-progress))
4279 ;; When not in an undo, check if we must commit the snippet
4280 ;; (user exited it).
4281 (yas--check-commit-snippet))))
4285 ;; The docstrings for some functions are generated dynamically
4286 ;; depending on the context.
4288 (put 'yas-expand 'function-documentation
4289 '(yas--expand-from-trigger-key-doc))
4290 (defun yas--expand-from-trigger-key-doc ()
4291 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4292 (let ((fallback-description
4293 (cond ((eq yas-fallback-behavior 'call-other-command)
4294 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4296 (format " call command `%s'." (pp-to-string fallback)))
4297 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4298 ((eq yas-fallback-behavior 'return-nil)
4301 ", defer to `yas-fallback-behaviour' (which see)"))))
4302 (concat "Expand a snippet before point. If no snippet
4303 expansion is possible,"
4304 fallback-description
4305 "\n\nOptional argument FIELD is for non-interactive use and is an
4306 object satisfying `yas--field-p' to restrict the expansion to.")))
4308 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4309 (defun yas--expand-from-keymap-doc ()
4310 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4311 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4312 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4313 (when (eq this-command 'describe-key)
4314 (let* ((vec (this-single-command-keys))
4315 (templates (mapcan #'(lambda (table)
4316 (yas--fetch table vec))
4317 (yas--get-snippet-tables)))
4318 (yas--direct-keymaps nil)
4319 (fallback (key-binding vec)))
4320 (concat "In this case, "
4322 (concat "these snippets are bound to this key:\n"
4323 (yas--template-pretty-list templates)
4324 "\n\nIf none of these expands, "))
4326 (format "fallback `%s' will be called." (pp-to-string fallback)))
4327 "no fallback keybinding is called."))))))
4329 (defun yas--template-pretty-list (templates)
4331 (yas-buffer-local-condition 'always))
4332 (dolist (plate templates)
4333 (setq acc (concat acc "\n*) "
4334 (propertize (concat "\\\\snippet `" (car plate) "'")
4335 'yasnippet (cdr plate)))))
4338 (define-button-type 'help-snippet-def
4339 :supertype 'help-xref
4340 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4341 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4343 (defun yas--snippet-description-finish-runonce ()
4344 "Final adjustments for the help buffer when snippets are concerned."
4345 (yas--create-snippet-xrefs)
4346 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4348 (defun yas--create-snippet-xrefs ()
4350 (goto-char (point-min))
4351 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4352 (let ((template (get-text-property (match-beginning 1)
4355 (help-xref-button 1 'help-snippet-def template)
4356 (kill-region (match-end 1) (match-end 0))
4357 (kill-region (match-beginning 0) (match-beginning 1)))))))
4361 (defvar yas-verbosity 4
4362 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4364 (defun yas--message (level message &rest args)
4365 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4366 (when (> yas-verbosity level)
4367 (message "%s" (apply #'yas--format message args))))
4369 (defun yas--format (format-control &rest format-args)
4370 (apply #'format (concat "[yas] " format-control) format-args))
4377 ;; `locate-dominating-file'
4378 ;; `region-active-p'
4380 ;; added for compatibility in emacsen < 23
4381 (unless (>= emacs-major-version 23)
4382 (unless (fboundp 'region-active-p)
4383 (defun region-active-p () (and transient-mark-mode mark-active)))
4385 (unless (fboundp 'locate-dominating-file)
4386 (defvar locate-dominating-stop-dir-regexp
4387 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4388 "Regexp of directory names which stop the search in `locate-dominating-file'.
4389 Any directory whose name matches this regexp will be treated like
4390 a kind of root directory by `locate-dominating-file' which will stop its search
4391 when it bumps into it.
4392 The default regexp prevents fruitless and time-consuming attempts to find
4393 special files in directories in which filenames are interpreted as hostnames,
4394 or mount points potentially requiring authentication as a different user.")
4396 (defun locate-dominating-file (file name)
4397 "Look up the directory hierarchy from FILE for a file named NAME.
4398 Stop at the first parent directory containing a file NAME,
4399 and return the directory. Return nil if not found."
4400 ;; We used to use the above locate-dominating-files code, but the
4401 ;; directory-files call is very costly, so we're much better off doing
4402 ;; multiple calls using the code in here.
4404 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4405 ;; `name' in /home or in /.
4406 (setq file (abbreviate-file-name file))
4409 (while (not (or root
4411 ;; FIXME: Disabled this heuristic because it is sometimes
4413 ;; As a heuristic, we stop looking up the hierarchy of
4414 ;; directories as soon as we find a directory belonging
4415 ;; to another user. This should save us from looking in
4416 ;; things like /net and /afs. This assumes that all the
4417 ;; files inside a project belong to the same user.
4418 ;; (let ((prev-user user))
4419 ;; (setq user (nth 2 (file-attributes file)))
4420 ;; (and prev-user (not (equal user prev-user))))
4421 (string-match locate-dominating-stop-dir-regexp file)))
4422 (setq try (file-exists-p (expand-file-name name file)))
4423 (cond (try (setq root file))
4424 ((equal file (setq file (file-name-directory
4425 (directory-file-name file))))
4429 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4430 ;; (when it execute forward-char) and interrupt the after change
4431 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4432 ;; invoked. Here's a way to reproduce it:
4434 ;; # open a *new* Emacs.
4435 ;; # load yasnippet.
4436 ;; # open a *new* .cpp file.
4437 ;; # input "inc" and press TAB to expand the snippet.
4438 ;; # select the `#include <...>` snippet.
4439 ;; # type inside `<>`
4441 (defadvice c-neutralize-syntax-in-CPP
4442 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4443 "Adviced `c-neutralize-syntax-in-CPP' to properly
4444 handle the `end-of-buffer' error fired in it by calling
4445 `forward-char' at the end of buffer."
4448 (error (message (error-message-string err)))))
4450 ;; disable c-electric-* serial command in YAS fields
4451 (add-hook 'c-mode-common-hook
4453 (dolist (k '(":" ">" ";" "<" "{" "}"))
4454 (define-key (symbol-value (make-local-variable 'yas-keymap))
4455 k 'self-insert-command))))
4457 ;;; Backward compatibility to yasnippet <= 0.7
4459 (defvar yas--exported-syms '(;; `defcustom's
4462 yas-prompt-functions
4464 yas-also-auto-indent-first-line
4466 yas-triggers-in-field
4467 yas-fallback-behavior
4468 yas-choose-keys-first
4469 yas-choose-tables-first
4472 yas-wrap-around-region
4475 yas-expand-only-for-last-commands
4476 yas-field-highlight-face
4478 ;; these vars can be customized as well
4484 yas-after-exit-snippet-hook
4485 yas-before-expand-snippet-hook
4486 yas-buffer-local-condition
4489 ;; prompting functions
4494 yas-completing-prompt
4497 ;; interactive functions
4502 yas-direct-keymaps-reload
4506 yas-compile-directory
4509 yas-expand-from-trigger-key
4510 yas-expand-from-keymap
4512 yas-visit-snippet-file
4514 yas-load-snippet-buffer
4517 yas-next-field-or-maybe-expand
4522 yas-exit-all-snippets
4523 yas-skip-and-clear-or-delete-char
4525 ;; symbols that I "exported" for use
4526 ;; in snippets and hookage
4544 yas-default-from-field
4547 yas-define-condition-cache
4548 yas-hippie-try-expand
4551 ;; debug definitions
4552 ;; yas-debug-snippet-vars
4553 ;; yas-exterminate-package
4556 ;; testing definitions
4557 ;; yas-should-expand
4558 ;; yas-should-not-expand
4560 ;; yas-make-file-or-dirs
4562 ;; yas-saving-variables
4563 ;; yas-call-with-snippet-dirs
4564 ;; yas-with-snippet-dirs
4566 "Exported yasnippet symbols.
4568 i.e. ones that I will try to keep in future yasnippet versions
4569 and ones that other elisp libraries can more or less safely rely
4572 (defvar yas--dont-backport '(yas-active-keys)
4573 "Exported symbols that don't map back to \"yas/*\" variants.")
4575 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4576 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4578 (make-obsolete-variable backported sym "yasnippet 0.8")
4579 (defvaralias backported sym))
4581 (make-obsolete backported sym "yasnippet 0.8")
4582 (defalias backported sym))))
4585 (provide 'yasnippet)
4587 ;;; yasnippet.el ends here
4590 ;; byte-compile-warnings: (not cl-functions)