1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is normally bound to TAB, but you can customize it in
67 ;; `yas-minor-mode-map'.
69 ;; M-x yas-load-directory
71 ;; Prompts you for a directory hierarchy of snippets to load.
73 ;; M-x yas-insert-snippet
75 ;; Prompts you for possible snippet expansion if that is
76 ;; possible according to buffer-local and snippet-local
77 ;; expansion conditions. With prefix argument, ignore these
80 ;; M-x yas-visit-snippet-file
82 ;; Prompts you for possible snippet expansions like
83 ;; `yas-insert-snippet', but instead of expanding it, takes
84 ;; you directly to the snippet definition's file, if it
87 ;; M-x yas-new-snippet
89 ;; Lets you create a new snippet file in the correct
90 ;; subdirectory of `yas-snippet-dirs', according to the
93 ;; M-x yas-load-snippet-buffer
95 ;; When editing a snippet, this loads the snippet. This is
96 ;; bound to "C-c C-c" while in the `snippet-mode' editing
99 ;; M-x yas-tryout-snippet
101 ;; When editing a snippet, this opens a new empty buffer,
102 ;; sets it to the appropriate major mode and inserts the
103 ;; snippet there, so you can see what it looks like. This is
104 ;; bound to "C-c C-t" while in `snippet-mode'.
106 ;; M-x yas-describe-tables
108 ;; Lists known snippets in a separate buffer. User is
109 ;; prompted as to whether only the currently active tables
110 ;; are to be displayed, or all the tables for all major
113 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
114 ;; can optionally use it the preferred "prompting method", putting in
115 ;; your .emacs file, for example:
117 ;; (require 'dropdown-list)
118 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
120 ;; yas-completing-prompt))
122 ;; Also check out the customization group
124 ;; M-x customize-group RET yasnippet RET
126 ;; If you use the customization group to set variables
127 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
128 ;; "yasnippet.el" is present in the `load-path' *before* the
129 ;; `custom-set-variables' is executed in your .emacs file.
131 ;; For more information and detailed usage, refer to the project page:
132 ;; http://github.com/capitaomorte/yasnippet
142 (defvar yas--editing-template)
143 (defvar yas--guessed-modes)
144 (defvar yas--indent-original-column)
145 (defvar yas--scheduled-jit-loads)
147 (defvar yas-selected-text)
148 (defvar yas-verbosity))
150 ;; Future-proof against obsoleting flet, see github #324
153 (unless (fboundp 'cl-flet)
154 (defalias 'cl-flet 'flet)
155 (put 'cl-flet 'lisp-indent-function 1)
156 (put 'cl-flet 'edebug-form-spec '((&rest (defun*)) cl-declarations body))))
159 ;;; User customizable variables
161 (defgroup yasnippet nil
162 "Yet Another Snippet extension"
165 (defvar yas--load-file-name load-file-name
166 "Store the filename that yasnippet.el was originally loaded from.")
168 (defcustom yas-snippet-dirs (remove nil
169 (list "~/.emacs.d/snippets"
170 (when yas--load-file-name
171 (concat (file-name-directory yas--load-file-name) "snippets"))))
172 "Directory or list of snippet dirs for each major mode.
174 The directory where user-created snippets are to be stored. Can
175 also be a list of directories. In that case, when used for
176 bulk (re)loading of snippets (at startup or via
177 `yas-reload-all'), directories appearing earlier in the list
178 shadow other dir's snippets. Also, the first directory is taken
179 as the default for storing the user's new snippets."
180 :type '(choice (string :tag "Single directory (string)")
181 (repeat :args (string) :tag "List of directories (strings)"))
184 :set #'(lambda (symbol new)
185 (let ((old (and (boundp symbol)
186 (symbol-value symbol))))
187 (set-default symbol new)
188 (unless (or (not (fboundp 'yas-reload-all))
192 (defun yas-snippet-dirs ()
193 "Returns `yas-snippet-dirs' (which see) as a list."
194 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
196 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
198 (defcustom yas-prompt-functions '(yas-x-prompt
200 yas-completing-prompt
203 "Functions to prompt for keys, templates, etc interactively.
205 These functions are called with the following arguments:
207 - PROMPT: A string to prompt the user
209 - CHOICES: a list of strings or objects.
211 - optional DISPLAY-FN : A function that, when applied to each of
212 the objects in CHOICES will return a string.
214 The return value of any function you put here should be one of
215 the objects in CHOICES, properly formatted with DISPLAY-FN (if
218 - To signal that your particular style of prompting is
219 unavailable at the moment, you can also have the function return
222 - To signal that the user quit the prompting process, you can
225 (signal 'quit \"user quit!\")."
226 :type '(repeat function)
229 (defcustom yas-indent-line 'auto
230 "Controls indenting applied to a recent snippet expansion.
232 The following values are possible:
234 - `fixed' Indent the snippet to the current column;
236 - `auto' Indent each line of the snippet with `indent-according-to-mode'
238 Every other value means don't apply any snippet-side indentation
239 after expansion (the manual per-line \"$>\" indentation still
241 :type '(choice (const :tag "Nothing" nothing)
242 (const :tag "Fixed" fixed)
243 (const :tag "Auto" auto))
246 (defcustom yas-also-auto-indent-first-line nil
247 "Non-nil means also auto indent first line according to mode.
249 Naturally this is only valid when `yas-indent-line' is `auto'"
253 (defcustom yas-snippet-revival t
254 "Non-nil means re-activate snippet fields after undo/redo."
258 (defcustom yas-triggers-in-field nil
259 "If non-nil, allow stacked expansions (snippets inside snippets).
261 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
266 (defcustom yas-fallback-behavior 'call-other-command
267 "How to act when `yas-expand' does *not* expand a snippet.
269 - `call-other-command' means try to temporarily disable YASnippet
270 and call the next command bound to whatever key was used to
273 - nil or the symbol `return-nil' mean do nothing. (and
274 `yas-expand' returns nil)
276 - A Lisp form (apply COMMAND . ARGS) means interactively call
277 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
278 with ARGS as arguments."
279 :type '(choice (const :tag "Call previous command" call-other-command)
280 (const :tag "Do nothing" return-nil))
283 (defcustom yas-choose-keys-first nil
284 "If non-nil, prompt for snippet key first, then for template.
286 Otherwise prompts for all possible snippet names.
288 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
292 (defcustom yas-choose-tables-first nil
293 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
295 Otherwise, user chooses between the merging together of all
298 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
302 (defcustom yas-use-menu 'abbreviate
303 "Display a YASnippet menu in the menu bar.
305 When non-nil, submenus for each snippet table will be listed
306 under the menu \"Yasnippet\".
308 - If set to `abbreviate', only the current major-mode
309 menu and the modes set in `yas-extra-modes' are listed.
311 - If set to `full', every submenu is listed
313 - It set to nil, don't display a menu at all (this requires a
314 `yas-reload-all' call if the menu is already visible).
316 Any other non-nil value, every submenu is listed."
317 :type '(choice (const :tag "Full" full)
318 (const :tag "Abbreviate" abbreviate)
319 (const :tag "No menu" nil))
322 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
323 (char-to-string ?\x21E5) ;; little ->| sign
325 "The text that will be used in menu to represent the trigger."
329 (defcustom yas-wrap-around-region nil
330 "If non-nil, snippet expansion wraps around selected region.
332 The wrapping occurs just before the snippet's exit marker. This
333 can be overridden on a per-snippet basis."
337 (defcustom yas-good-grace t
338 "If non-nil, don't raise errors in inline elisp evaluation.
340 An error string \"[yas] error\" is returned instead."
344 (defcustom yas-visit-from-menu nil
345 "If non-nil visit snippets's files from menu, instead of expanding them.
347 This can only work when snippets are loaded from files."
351 (defcustom yas-expand-only-for-last-commands nil
352 "List of `last-command' values to restrict tab-triggering to, or nil.
354 Leave this set at nil (the default) to be able to trigger an
355 expansion simply by placing the cursor after a valid tab trigger,
356 using whichever commands.
358 Optionally, set this to something like '(self-insert-command) if
359 you to wish restrict expansion to only happen when the last
360 letter of the snippet tab trigger was typed immediately before
361 the trigger key itself."
362 :type '(repeat function)
365 ;; Only two faces, and one of them shouldn't even be used...
367 (defface yas-field-highlight-face
368 '((t (:inherit 'region)))
369 "The face used to highlight the currently active field of a snippet"
372 (defface yas--field-debug-face
374 "The face used for debugging some overlays normally hidden"
378 (defvar yas-keymap (let ((map (make-sparse-keymap)))
379 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
380 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
381 (define-key map [(shift tab)] 'yas-prev-field)
382 (define-key map [backtab] 'yas-prev-field)
383 (define-key map (kbd "C-g") 'yas-abort-snippet)
384 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
386 "The active keymap while a snippet expansion is in progress.")
388 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
389 "List of character syntaxes used to find a trigger key before point.
390 The list is tried in the order while scanning characters
391 backwards from point. For example, if the list is '(\"w\" \"w_\")
392 first look for trigger keys which are composed exclusively of
393 \"word\"-syntax characters, and then, if that fails, look for
394 keys which are either of \"word\" or \"symbol\"
395 syntax. Triggering after
399 will, according to the \"w\" element first try \"bar\". If that
400 isn't a trigger key, \"foo-bar\" is tried, respecting a second
403 (defvar yas-after-exit-snippet-hook
405 "Hooks to run after a snippet exited.
407 The hooks will be run in an environment where some variables bound to
410 `yas-snippet-beg' : The beginning of the region of the snippet.
412 `yas-snippet-end' : Similar to beg.
414 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
416 (defvar yas-before-expand-snippet-hook
418 "Hooks to run just before expanding a snippet.")
420 (defvar yas-buffer-local-condition
421 '(if (and (or (fourth (syntax-ppss))
422 (fifth (syntax-ppss)))
423 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
424 '(require-snippet-condition . force-in-comment)
426 "Snippet expanding condition.
428 This variable is a Lisp form which is evaluated every time a
429 snippet expansion is attempted:
431 * If it evaluates to nil, no snippets can be expanded.
433 * If it evaluates to the a cons (require-snippet-condition
436 * Snippets bearing no \"# condition:\" directive are not
439 * Snippets bearing conditions that evaluate to nil (or
440 produce an error) won't be considered.
442 * If the snippet has a condition that evaluates to non-nil
445 * If REQUIREMENT is t, the snippet is considered
447 * If REQUIREMENT is `eq' RESULT, the snippet is
450 * Otherwise, the snippet is not considered.
452 * If it evaluates to the symbol 'always, all snippets are
453 considered for expansion, regardless of any conditions.
455 * If it evaluates to t or some other non-nil value
457 * Snippet bearing no conditions, or conditions that
458 evaluate to non-nil, are considered for expansion.
460 * Otherwise, the snippet is not considered.
462 Here's an example preventing snippets from being expanded from
463 inside comments, in `python-mode' only, with the exception of
464 snippets returning the symbol 'force-in-comment in their
467 (add-hook 'python-mode-hook
469 (setq yas-buffer-local-condition
470 '(if (python-in-string/comment)
471 '(require-snippet-condition . force-in-comment)
474 The default value is similar, it filters out potential snippet
475 expansions inside comments and string literals, unless the
476 snippet itself contains a condition that returns the symbol
477 `force-in-comment'.")
480 ;;; Internal variables
482 (defvar yas--version "0.8.0 (beta)")
484 (defvar yas--menu-table (make-hash-table)
485 "A hash table of MAJOR-MODE symbols to menu keymaps.")
487 (defvar yas--known-modes
488 '(ruby-mode rst-mode markdown-mode)
489 "A list of mode which is well known but not part of Emacs.")
491 (defvar yas--escaped-characters
492 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
493 "List of characters which *might* need to be escaped.")
495 (defconst yas--field-regexp
496 "${\\([0-9]+:\\)?\\([^}]*\\)}"
497 "A regexp to *almost* recognize a field.")
499 (defconst yas--multi-dollar-lisp-expression-regexp
500 "$+[ \t\n]*\\(([^)]*)\\)"
501 "A regexp to *almost* recognize a \"$(...)\" expression.")
503 (defconst yas--backquote-lisp-expression-regexp
505 "A regexp to recognize a \"`lisp-expression`\" expression." )
507 (defconst yas--transform-mirror-regexp
508 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
509 "A regexp to *almost* recognize a mirror with a transform.")
511 (defconst yas--simple-mirror-regexp
513 "A regexp to recognize a simple mirror.")
515 (defvar yas--snippet-id-seed 0
516 "Contains the next id for a snippet.")
518 (defun yas--snippet-next-id ()
519 (let ((id yas--snippet-id-seed))
520 (incf yas--snippet-id-seed)
526 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
527 (defvar last-buffer-undo-list nil)
529 (defvar yas--minor-mode-menu nil
530 "Holds the YASnippet menu.")
532 (defun yas--init-minor-keymap ()
533 "Set up the `yas-minor-mode' keymap."
534 (let ((map (make-sparse-keymap)))
536 (easy-menu-define yas--minor-mode-menu
538 "Menu used when `yas-minor-mode' is active."
541 ["Expand trigger" yas-expand
542 :help "Possibly expand tab trigger before point"]
543 ["Insert at point..." yas-insert-snippet
544 :help "Prompt for an expandable snippet and expand it at point"]
545 ["New snippet..." yas-new-snippet
546 :help "Create a new snippet in an appropriate directory"]
547 ["Visit snippet file..." yas-visit-snippet-file
548 :help "Prompt for an expandable snippet and find its file"]
550 ("Snippet menu behaviour"
551 ["Visit snippets" (setq yas-visit-from-menu t)
552 :help "Visit snippets from the menu"
553 :active t :style radio :selected yas-visit-from-menu]
554 ["Expand snippets" (setq yas-visit-from-menu nil)
555 :help "Expand snippets from the menu"
556 :active t :style radio :selected (not yas-visit-from-menu)]
558 ["Show all known modes" (setq yas-use-menu 'full)
559 :help "Show one snippet submenu for each loaded table"
560 :active t :style radio :selected (eq yas-use-menu 'full)]
561 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
562 :help "Show only snippet submenus for the current active modes"
563 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
565 ["Auto" (setq yas-indent-line 'auto)
566 :help "Indent each line of the snippet with `indent-according-to-mode'"
567 :active t :style radio :selected (eq yas-indent-line 'auto)]
568 ["Fixed" (setq yas-indent-line 'fixed)
569 :help "Indent the snippet to the current column"
570 :active t :style radio :selected (eq yas-indent-line 'fixed)]
571 ["None" (setq yas-indent-line 'none)
572 :help "Don't apply any particular snippet indentation after expansion"
573 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
575 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
576 (not yas-also-auto-indent-first-line))
577 :help "When auto-indenting also, auto indent the first line menu"
578 :active (eq yas-indent-line 'auto)
579 :style toggle :selected yas-also-auto-indent-first-line]
582 ["System X-widget" (setq yas-prompt-functions
584 (remove 'yas-x-prompt
585 yas-prompt-functions)))
586 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
587 :active t :style radio :selected (eq (car yas-prompt-functions)
589 ["Dropdown-list" (setq yas-prompt-functions
590 (cons 'yas-dropdown-prompt
591 (remove 'yas-dropdown-prompt
592 yas-prompt-functions)))
593 :help "Use a special dropdown list"
594 :active t :style radio :selected (eq (car yas-prompt-functions)
595 'yas-dropdown-prompt)]
596 ["Ido" (setq yas-prompt-functions
597 (cons 'yas-ido-prompt
598 (remove 'yas-ido-prompt
599 yas-prompt-functions)))
600 :help "Use an ido-style minibuffer prompt"
601 :active t :style radio :selected (eq (car yas-prompt-functions)
603 ["Completing read" (setq yas-prompt-functions
604 (cons 'yas-completing-prompt
605 (remove 'yas-completing-prompt
606 yas-prompt-functions)))
607 :help "Use a normal minibuffer prompt"
608 :active t :style radio :selected (eq (car yas-prompt-functions)
609 'yas-completing-prompt)]
612 ["Wrap region in exit marker"
613 (setq yas-wrap-around-region
614 (not yas-wrap-around-region))
615 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
616 :style toggle :selected yas-wrap-around-region]
617 ["Allow stacked expansions "
618 (setq yas-triggers-in-field
619 (not yas-triggers-in-field))
620 :help "If non-nil allow snippets to be triggered inside other snippet fields"
621 :style toggle :selected yas-triggers-in-field]
622 ["Revive snippets on undo "
623 (setq yas-snippet-revival
624 (not yas-snippet-revival))
625 :help "If non-nil allow snippets to become active again after undo"
626 :style toggle :selected yas-snippet-revival]
629 (not yas-good-grace))
630 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
631 :style toggle :selected yas-good-grace]
634 ["Load snippets..." yas-load-directory
635 :help "Load snippets from a specific directory"]
636 ["Reload everything" yas-reload-all
637 :help "Cleanup stuff, reload snippets, rebuild menus"]
639 :help "Display some information about YASnippet"])))
641 ;; Now for the stuff that has direct keybindings
643 (define-key map [(tab)] 'yas-expand)
644 (define-key map (kbd "TAB") 'yas-expand)
645 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
646 (define-key map "\C-c&\C-n" 'yas-new-snippet)
647 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
650 (defvar yas-minor-mode-map (yas--init-minor-keymap)
651 "The keymap used when `yas-minor-mode' is active.")
653 (defvar yas--tables (make-hash-table)
654 "A hash table of mode symbols to `yas--table' objects.")
656 (defvar yas--parents (make-hash-table)
657 "A hash table of mode symbols do lists of direct parent mode symbols.
659 This list is populated when reading the \".yas-parents\" files
660 found when traversing snippet directories with
661 `yas-load-directory'.
663 There might be additional parenting information stored in the
664 `derived-mode-parent' property of some mode symbols, but that is
667 (defvar yas--direct-keymaps (list)
668 "Keymap alist supporting direct snippet keybindings.
670 This variable is placed in `emulation-mode-map-alists'.
672 Its elements looks like (TABLE-NAME . KEYMAP). They're
673 instantiated on `yas-reload-all' but KEYMAP is added to only when
674 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
675 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
676 defined direct keybindings to the command
677 `yas-expand-from-keymap' which then which snippet to expand.")
679 (defun yas-direct-keymaps-reload ()
680 "Force reload the direct keybinding for active snippet tables."
682 (setq yas--direct-keymaps nil)
683 (maphash #'(lambda (name table)
684 (push (cons (intern (format "yas--direct-%s" name))
685 (yas--table-direct-keymap table))
686 yas--direct-keymaps))
689 (defun yas--modes-to-activate ()
690 "Compute list of mode symbols that are active for `yas-expand'
692 (let ((modes-to-activate (list major-mode))
694 (while (setq mode (get mode 'derived-mode-parent))
695 (push mode modes-to-activate))
696 (dolist (mode (yas-extra-modes))
697 (push mode modes-to-activate))
699 (append modes-to-activate
700 (mapcan #'(lambda (mode)
701 (yas--all-parents mode))
702 modes-to-activate)))))
704 (defvar yas-minor-mode-hook nil
705 "Hook run when `yas-minor-mode' is turned on.")
708 (define-minor-mode yas-minor-mode
709 "Toggle YASnippet mode.
711 When YASnippet mode is enabled, `yas-expand', normally bound to
712 the TAB key, expands snippets of code depending on the major
715 With no argument, this command toggles the mode.
716 positive prefix argument turns on the mode.
717 Negative prefix argument turns off the mode.
720 \\{yas-minor-mode-map}"
722 ;; The indicator for the mode line.
725 (cond (yas-minor-mode
726 ;; Install the direct keymaps in `emulation-mode-map-alists'
727 ;; (we use `add-hook' even though it's not technically a hook,
728 ;; but it works). Then define variables named after modes to
729 ;; index `yas--direct-keymaps'.
731 ;; Also install the post-command-hook.
733 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
734 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
735 ;; Set the `yas--direct-%s' vars for direct keymap expansion
737 (dolist (mode (yas--modes-to-activate))
738 (let ((name (intern (format "yas--direct-%s" mode))))
739 (set-default name nil)
740 (set (make-local-variable name) t)))
743 (yas--load-pending-jits))
745 ;; Uninstall the direct keymaps and the post-command hook
747 (remove-hook 'post-command-hook 'yas--post-command-handler t)
748 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
750 (defvar yas-dont-activate '(minibufferp)
751 "If non-nil don't let `yas-minor-mode-on' activate for this buffer.
753 If a function, then its result is used.
755 If a list of functions, then all functions must return nil to
756 activate yas for this buffer.
758 `yas-minor-mode-on' is usually called by `yas-global-mode' so
759 this effectively lets you define exceptions to the \"global\"
760 behaviour. Can also be a function of zero arguments.")
761 (make-variable-buffer-local 'yas-dont-activate)
763 (defun yas-minor-mode-on ()
764 "Turn on YASnippet minor mode.
766 Honour `yas-dont-activate', which see."
768 ;; Check `yas-dont-activate'
769 (unless (cond ((functionp yas-dont-activate)
770 (funcall yas-dont-activate))
771 ((consp yas-dont-activate)
772 (some #'funcall yas-dont-activate))
777 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
781 (defun yas--global-mode-reload-with-jit-maybe ()
782 "Run `yas-reload-all' when `yas-global-mode' is on."
783 (when yas-global-mode (yas-reload-all)))
785 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
787 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
790 (defvar yas--font-lock-keywords
791 (append '(("^#.*$" . font-lock-comment-face))
792 lisp-font-lock-keywords
793 lisp-font-lock-keywords-1
794 lisp-font-lock-keywords-2
796 (0 font-lock-keyword-face)
797 (1 font-lock-string-face t))
799 (0 font-lock-keyword-face)
800 (1 font-lock-warning-face t))
801 ("${" font-lock-keyword-face)
802 ("$[0-9]+?" font-lock-preprocessor-face)
803 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
805 (0 font-lock-keyword-face)))))
807 (defun yas--init-major-keymap ()
808 "Setup YASnippet major-mode keymap."
809 (let ((map (make-sparse-keymap)))
810 (easy-menu-define nil
812 "Menu used when snippet-mode is active."
814 (mapcar #'(lambda (ent)
816 (define-key map (third ent) (second ent)))
817 (vector (first ent) (second ent) t))
819 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
820 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
823 (defvar snippet-mode-map
824 (yas--init-major-keymap)
825 "The keymap used when `snippet-mode' is active.")
828 (define-derived-mode snippet-mode text-mode "Snippet"
829 "A mode for editing yasnippets"
830 (setq font-lock-defaults '(yas--font-lock-keywords))
831 (set (make-local-variable 'require-final-newline) nil)
832 (set (make-local-variable 'comment-start) "#")
833 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
837 ;;; Internal structs for template management
839 (defstruct (yas--template (:constructor yas--make-blank-template))
840 "A template for a snippet."
850 group ;; as dictated by the #group: directive or .yas-make-groups
851 perm-group ;; as dictated by `yas-define-menu'
855 (defun yas--populate-template (template &rest args)
856 "Helper function to populate TEMPLATE with properties."
860 (position (intern (substring (symbol-name (car args)) 1))
861 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
863 (setq args (cddr args)))
866 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
867 "A table to store snippets for a particular mode.
869 Has the following fields:
873 A symbol name normally corresponding to a major mode, but can
874 also be a pseudo major-mode to be referenced in
875 `yas-extra-modes', for example.
879 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
880 a string or a vector, where the former is the snippet's trigger
881 and the latter means it's a direct keybinding. NAMEHASH is yet
882 another hash of (NAME . TEMPLATE) where NAME is the snippet's
883 name and TEMPLATE is a `yas--template' object.
885 `yas--table-direct-keymap'
887 A keymap for the snippets in this table that have direct
888 keybindings. This is kept in sync with the keyhash, i.e., all
889 the elements of the keyhash that are vectors appear here as
890 bindings to `yas-expand-from-keymap'.
892 `yas--table-uuidhash'
894 A hash table mapping snippets uuid's to the same `yas--template'
895 objects. A snippet uuid defaults to the snippet's name.
898 (hash (make-hash-table :test 'equal))
899 (uuidhash (make-hash-table :test 'equal))
901 (direct-keymap (make-sparse-keymap)))
903 (defun yas--get-template-by-uuid (mode uuid)
904 "Find the snippet template in MODE by its UUID."
905 (let* ((table (gethash mode yas--tables mode)))
907 (gethash uuid (yas--table-uuidhash table)))))
909 ;; Apropos storing/updating in TABLE, this works in two steps:
911 ;; 1. `yas--remove-template-by-uuid' removes any
912 ;; keyhash-namehash-template mappings from TABLE, grabbing the
913 ;; snippet by its uuid. Also removes mappings from TABLE's
914 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
915 ;; of potentially stale menu bindings right?.)
917 ;; 2. `yas--add-template' adds this all over again.
919 ;; Create a new or add to an existing keyhash-namehash mapping.
921 ;; For reference on understanding this, consider three snippet
924 ;; A: # name: The Foo
926 ;; # binding: C-c M-l
928 ;; B: # name: Mrs Foo
931 ;; C: # name: The Bar
932 ;; # binding: C-c M-l
937 ;; keyhash namehashes(3) yas--template structs(4)
938 ;; -----------------------------------------------------
941 ;; "foo" ---> "The Foo" ---> [yas--template A] |
942 ;; "Mrs Foo" ---> [yas--template B] |
944 ;; [C-c M-l] ---> "The Foo" -------------------------/
945 ;; "The Bar" ---> [yas--template C]
947 ;; "baz" ---> "Baz" ---> [yas--template D]
949 ;; Additionally, since uuid defaults to the name, we have a
950 ;; `yas--table-uuidhash' for TABLE
952 ;; uuidhash yas--template structs
953 ;; -------------------------------
954 ;; "The Foo" ---> [yas--template A]
955 ;; "Mrs Foo" ---> [yas--template B]
956 ;; "The Bar" ---> [yas--template C]
957 ;; "Baz" ---> [yas--template D]
959 ;; FIXME: the more I look at this data-structure the more I think I'm
960 ;; stupid. There has to be an easier way (but beware lots of code
963 (defun yas--remove-template-by-uuid (table uuid)
964 "Remove from TABLE a template identified by UUID."
965 (let ((template (gethash uuid (yas--table-uuidhash table))))
967 (let* ((name (yas--template-name template))
969 ;; Remove the name from each of the targeted namehashes
971 (maphash #'(lambda (k v)
972 (let ((template (gethash name v)))
974 (eq uuid (yas--template-uuid template)))
976 (when (zerop (hash-table-count v))
977 (push k empty-keys)))))
978 (yas--table-hash table))
979 ;; Remove the namehash themselves if they've become empty
981 (dolist (key empty-keys)
983 (define-key (yas--table-direct-keymap table) key nil))
984 (remhash key (yas--table-hash table)))
986 ;; Finally, remove the uuid from the uuidhash
988 (remhash uuid (yas--table-uuidhash table))))))
990 (defun yas--add-template (table template)
991 "Store in TABLE the snippet template TEMPLATE.
993 KEY can be a string (trigger key) of a vector (direct
995 (let ((name (yas--template-name template))
996 (key (yas--template-key template))
997 (keybinding (yas--template-keybinding template))
998 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
999 (dolist (k (remove nil (list key keybinding)))
1003 (yas--table-hash table))
1005 (make-hash-table :test 'equal)
1006 (yas--table-hash table))))
1008 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1010 ;; Update TABLE's `yas--table-uuidhash'
1011 (puthash (yas--template-uuid template)
1013 (yas--table-uuidhash table))))
1015 (defun yas--update-template (table template)
1016 "Add or update TEMPLATE in TABLE.
1018 Also takes care of adding and updating to the associated menu."
1019 ;; Remove from table by uuid
1021 (yas--remove-template-by-uuid table (yas--template-uuid template))
1022 ;; Add to table again
1024 (yas--add-template table template)
1025 ;; Take care of the menu
1028 (yas--update-template-menu table template)))
1030 (defun yas--update-template-menu (table template)
1031 "Update every menu-related for TEMPLATE."
1032 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1033 (key (yas--template-key template))
1034 (keybinding (yas--template-keybinding template)))
1035 ;; The snippet might have changed name or keys, so update
1036 ;; user-visible strings
1038 (unless (eq (cdr menu-binding-pair) :none)
1039 ;; the menu item name
1041 (setf (cadar menu-binding-pair) (yas--template-name template))
1042 ;; the :keys information (also visible to the user)
1043 (setf (getf (cdr (car menu-binding-pair)) :keys)
1044 (or (and keybinding (key-description keybinding))
1045 (and key (concat key yas-trigger-symbol))))))
1046 (unless (yas--template-menu-managed-by-yas-define-menu template)
1048 (yas--menu-keymap-get-create (yas--table-mode table)
1049 (mapcar #'yas--table-mode
1050 (yas--table-parents table))))
1051 (group (yas--template-group template)))
1052 ;; Remove from menu keymap
1054 (assert menu-keymap)
1055 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1057 ;; Add necessary subgroups as necessary.
1059 (dolist (subgroup group)
1060 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1061 (unless (and subgroup-keymap
1062 (keymapp subgroup-keymap))
1063 (setq subgroup-keymap (make-sparse-keymap))
1064 (define-key menu-keymap (vector (make-symbol subgroup))
1065 `(menu-item ,subgroup ,subgroup-keymap)))
1066 (setq menu-keymap subgroup-keymap)))
1068 ;; Add this entry to the keymap
1070 (define-key menu-keymap
1071 (vector (make-symbol (yas--template-uuid template)))
1072 (car (yas--template-menu-binding-pair template))))))
1074 (defun yas--namehash-templates-alist (namehash)
1075 "Return NAMEHASH as an alist."
1077 (maphash #'(lambda (k v)
1078 (push (cons k v) alist))
1082 (defun yas--fetch (table key)
1083 "Fetch templates in TABLE by KEY.
1085 Return a list of cons (NAME . TEMPLATE) where NAME is a
1086 string and TEMPLATE is a `yas--template' structure."
1087 (let* ((keyhash (yas--table-hash table))
1088 (namehash (and keyhash (gethash key keyhash))))
1090 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1093 ;;; Filtering/condition logic
1095 (defun yas--eval-condition (condition)
1102 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1106 (defun yas--filter-templates-by-condition (templates)
1107 "Filter the templates using the applicable condition.
1109 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1110 string and TEMPLATE is a `yas--template' structure.
1112 This function implements the rules described in
1113 `yas-buffer-local-condition'. See that variables documentation."
1114 (let ((requirement (yas--require-template-specific-condition-p)))
1115 (if (eq requirement 'always)
1117 (remove-if-not #'(lambda (pair)
1118 (yas--template-can-expand-p
1119 (yas--template-condition (cdr pair)) requirement))
1122 (defun yas--require-template-specific-condition-p ()
1123 "Decides if this buffer requests/requires snippet-specific
1124 conditions to filter out potential expansions."
1125 (if (eq 'always yas-buffer-local-condition)
1127 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1128 (yas--eval-condition yas-buffer-local-condition))
1129 yas-buffer-local-condition)))
1130 (when local-condition
1131 (if (eq local-condition t)
1133 (and (consp local-condition)
1134 (eq 'require-snippet-condition (car local-condition))
1135 (symbolp (cdr local-condition))
1136 (cdr local-condition)))))))
1138 (defun yas--template-can-expand-p (condition requirement)
1139 "Evaluates CONDITION and REQUIREMENT and returns a boolean."
1140 (let* ((result (or (null condition)
1141 (yas--eval-condition condition))))
1142 (cond ((eq requirement t)
1145 (eq requirement result)))))
1147 (defun yas--all-parents (mode)
1148 "Returns a list of all parent modes of MODE."
1149 (let ((parents (gethash mode yas--parents)))
1151 (mapcan #'yas--all-parents parents))))
1153 (defun yas--table-templates (table)
1156 (maphash #'(lambda (key namehash)
1157 (maphash #'(lambda (name template)
1158 (push (cons name template) acc))
1160 (yas--table-hash table))
1161 (yas--filter-templates-by-condition acc))))
1163 (defun yas--current-key ()
1164 "Get the key under current position. A key is used to find
1165 the template of a snippet in the current snippet-table."
1166 (let ((start (point))
1168 (syntaxes yas-key-syntaxes)
1172 (while (and (not done) syntaxes)
1173 (setq syntax (car syntaxes))
1174 (setq syntaxes (cdr syntaxes))
1176 (skip-syntax-backward syntax)
1177 (setq start (point)))
1179 (mapcan #'(lambda (table)
1180 (yas--fetch table (buffer-substring-no-properties start end)))
1181 (yas--get-snippet-tables)))
1190 (defun yas--table-all-keys (table)
1191 "Get trigger keys of all active snippets in TABLE."
1193 (maphash #'(lambda (key namehash)
1194 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1196 (yas--table-hash table))
1199 (defun yas--table-mode (table)
1200 (intern (yas--table-name table)))
1203 ;;; Internal functions:
1205 (defun yas--real-mode? (mode)
1206 "Try to find out if MODE is a real mode.
1208 The MODE bound to a function (like `c-mode') is considered real
1209 mode. Other well known mode like `ruby-mode' which is not part of
1210 Emacs might not bound to a function until it is loaded. So
1211 yasnippet keeps a list of modes like this to help the judgment."
1213 (find mode yas--known-modes)))
1215 (defun yas--eval-lisp (form)
1216 "Evaluate FORM and convert the result to string."
1217 (let ((retval (catch 'yas--exception
1223 (let ((result (eval form)))
1225 (format "%s" result))))))
1226 (error (if yas-good-grace
1227 (yas--format "elisp error! %s" (error-message-string err))
1228 (error (yas--format "elisp error: %s"
1229 (error-message-string err)))))))))
1230 (when (and (consp retval)
1231 (eq 'yas--exception (car retval)))
1232 (error (cdr retval)))
1235 (defun yas--eval-lisp-no-saves (form)
1238 (error (if yas-good-grace
1239 (yas--format "elisp error! %s" (error-message-string err))
1240 (error (yas--format "elisp error: %s"
1241 (error-message-string err)))))))
1243 (defun yas--read-lisp (string &optional nil-on-error)
1244 "Read STRING as a elisp expression and return it.
1246 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1247 return an expression that when evaluated will issue an error."
1250 (error (and (not nil-on-error)
1251 `(error (error-message-string ,err))))))
1253 (defun yas--read-keybinding (keybinding)
1254 "Read KEYBINDING as a snippet keybinding, return a vector."
1255 (when (and keybinding
1256 (not (string-match "keybinding" keybinding)))
1258 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1260 (read-kbd-macro keybinding 'need-vector))))
1263 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1264 keybinding (error-message-string err))
1267 (defvar yas-extra-modes nil
1268 "If non-nil, also lookup snippets for this/these modes.
1270 Can be a symbol or a list of symbols.
1272 This variable probably makes more sense as buffer-local, so
1273 ensure your use `make-local-variable' when you set it.")
1274 (defun yas-extra-modes ()
1275 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1276 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1278 (defun yas--table-get-create (mode)
1279 "Get or create the snippet table corresponding to MODE."
1280 (let ((table (gethash mode
1283 (setq table (yas--make-snippet-table (symbol-name mode)))
1284 (puthash mode table yas--tables)
1285 (push (cons (intern (format "yas--direct-%s" mode))
1286 (yas--table-direct-keymap table))
1287 yas--direct-keymaps))
1290 (defun yas--get-snippet-tables ()
1291 "Get snippet tables for current buffer.
1293 Return a list of `yas--table' objects. The list of modes to
1294 consider is returned by `yas--modes-to-activate'"
1296 (mapcar #'(lambda (mode-name)
1297 (gethash mode-name yas--tables))
1298 (yas--modes-to-activate))))
1300 (defun yas--menu-keymap-get-create (mode &optional parents)
1301 "Get or create the menu keymap for MODE and its PARENTS.
1303 This may very well create a plethora of menu keymaps and arrange
1304 them all in `yas--menu-table'"
1305 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1306 (puthash mode (make-sparse-keymap) yas--menu-table))))
1307 (mapc #'yas--menu-keymap-get-create parents)
1308 (define-key yas--minor-mode-menu (vector mode)
1309 `(menu-item ,(symbol-name mode) ,menu-keymap
1310 :visible (yas--show-menu-p ',mode)))
1313 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1314 ;;; Template-related and snippet loading functions
1316 (defun yas--parse-template (&optional file)
1317 "Parse the template in the current buffer.
1319 Optional FILE is the absolute file name of the file being
1322 Optional GROUP is the group where the template is to go,
1323 otherwise we attempt to calculate it from FILE.
1325 Return a snippet-definition, i.e. a list
1327 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1329 If the buffer contains a line of \"# --\" then the contents above
1330 this line are ignored. Directives can set most of these with the syntax:
1332 # directive-name : directive-value
1334 Here's a list of currently recognized directives:
1345 (goto-char (point-min))
1346 (let* ((type 'snippet)
1348 (file-name-nondirectory file)))
1354 (yas--calculate-group file)))
1358 (if (re-search-forward "^# --\n" nil t)
1359 (progn (setq template
1360 (buffer-substring-no-properties (point)
1362 (setq bound (point))
1363 (goto-char (point-min))
1364 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1365 (when (string= "uuid" (match-string-no-properties 1))
1366 (setq uuid (match-string-no-properties 2)))
1367 (when (string= "type" (match-string-no-properties 1))
1368 (setq type (if (string= "command" (match-string-no-properties 2))
1371 (when (string= "key" (match-string-no-properties 1))
1372 (setq key (match-string-no-properties 2)))
1373 (when (string= "name" (match-string-no-properties 1))
1374 (setq name (match-string-no-properties 2)))
1375 (when (string= "condition" (match-string-no-properties 1))
1376 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1377 (when (string= "group" (match-string-no-properties 1))
1378 (setq group (match-string-no-properties 2)))
1379 (when (string= "expand-env" (match-string-no-properties 1))
1380 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1382 (when (string= "binding" (match-string-no-properties 1))
1383 (setq binding (match-string-no-properties 2)))))
1385 (buffer-substring-no-properties (point-min) (point-max))))
1386 (unless (or key binding)
1387 (setq key (and file (file-name-nondirectory file))))
1388 (when (eq type 'command)
1389 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1391 (setq group (split-string group "\\.")))
1392 (list key template name condition group expand-env file binding uuid)))
1394 (defun yas--calculate-group (file)
1395 "Calculate the group for snippet file path FILE."
1396 (let* ((dominating-dir (locate-dominating-file file
1397 ".yas-make-groups"))
1398 (extra-path (and dominating-dir
1399 (replace-regexp-in-string (concat "^"
1400 (expand-file-name dominating-dir))
1402 (expand-file-name file))))
1403 (extra-dir (and extra-path
1404 (file-name-directory extra-path)))
1405 (group (and extra-dir
1406 (replace-regexp-in-string "/"
1408 (directory-file-name extra-dir)))))
1411 (defun yas--subdirs (directory &optional filep)
1412 "Return subdirs or files of DIRECTORY according to FILEP."
1413 (remove-if (lambda (file)
1414 (or (string-match "^\\."
1415 (file-name-nondirectory file))
1416 (string-match "^#.*#$"
1417 (file-name-nondirectory file))
1419 (file-name-nondirectory file))
1421 (file-directory-p file)
1422 (not (file-directory-p file)))))
1423 (directory-files directory t)))
1425 (defun yas--make-menu-binding (template)
1426 (let ((mode (yas--table-mode (yas--template-table template))))
1427 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1429 (defun yas--expand-or-visit-from-menu (mode uuid)
1430 (let* ((table (yas--table-get-create mode))
1431 (yas--current-template (and table
1432 (gethash uuid (yas--table-uuidhash table)))))
1433 (when yas--current-template
1434 (if yas-visit-from-menu
1435 (yas--visit-snippet-file-1 yas--current-template)
1436 (let ((where (if (region-active-p)
1437 (cons (region-beginning) (region-end))
1438 (cons (point) (point)))))
1439 (yas-expand-snippet (yas--template-content yas--current-template)
1442 (yas--template-expand-env yas--current-template)))))))
1444 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1445 ;; Popping up for keys and templates
1447 (defvar yas--x-pretty-prompt-templates nil
1448 "If non-nil, attempt to prompt for templates like TextMate.")
1451 (defun yas--prompt-for-template (templates &optional prompt)
1452 "Interactively choose a template from the list TEMPLATES.
1454 TEMPLATES is a list of `yas--template'.
1456 Optional PROMPT sets the prompt to use."
1459 (sort templates #'(lambda (t1 t2)
1460 (< (length (yas--template-name t1))
1461 (length (yas--template-name t2))))))
1462 (if yas--x-pretty-prompt-templates
1463 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1464 (some #'(lambda (fn)
1465 (funcall fn (or prompt "Choose a snippet: ")
1467 #'yas--template-name))
1468 yas-prompt-functions))))
1470 (defun yas--prompt-for-keys (keys &optional prompt)
1471 "Interactively choose a template key from the list KEYS.
1473 Optional PROMPT sets the prompt to use."
1475 (some #'(lambda (fn)
1476 (funcall fn (or prompt "Choose a snippet key: ") keys))
1477 yas-prompt-functions)))
1479 (defun yas--prompt-for-table (tables &optional prompt)
1480 "Interactively choose a table from the list TABLES.
1482 Optional PROMPT sets the prompt to use."
1484 (some #'(lambda (fn)
1485 (funcall fn (or prompt "Choose a snippet table: ")
1488 yas-prompt-functions)))
1490 (defun yas-x-prompt (prompt choices &optional display-fn)
1491 "Display choices in a x-window prompt."
1492 ;; FIXME: HACK: if we notice that one of the objects in choices is
1493 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1495 ;; This would be better implemented by passing CHOICES as a
1496 ;; structured tree rather than a list. Modifications would go as far
1497 ;; up as `yas--all-templates' I think.
1499 (when (and window-system choices)
1501 (let (menu d) ;; d for display
1503 (setq d (or (and display-fn (funcall display-fn c))
1506 (push (cons (concat " " d) c) menu))
1508 (push (car d) menu))))
1509 (setq menu (list prompt (push "title" menu)))
1510 (x-popup-menu (if (fboundp 'posn-at-point)
1511 (let ((x-y (posn-x-y (posn-at-point (point)))))
1512 (list (list (+ (car x-y) 10)
1520 (defun yas--x-pretty-prompt-templates (prompt templates)
1521 "Display TEMPLATES, grouping neatly by table name."
1522 (let ((organized (make-hash-table :test #'equal))
1526 (dolist (tl templates)
1527 (puthash (yas--template-table tl)
1529 (gethash (yas--template-table tl) organized))
1531 (setq more-than-one-table (> (hash-table-count organized) 1))
1532 (setq prefix (if more-than-one-table
1534 (if more-than-one-table
1535 (maphash #'(lambda (table templates)
1536 (push (yas--table-name table) menu)
1537 (dolist (tl templates)
1538 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1539 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1541 (setq menu (nreverse menu))
1542 (or (x-popup-menu (if (fboundp 'posn-at-point)
1543 (let ((x-y (posn-x-y (posn-at-point (point)))))
1544 (list (list (+ (car x-y) 10)
1548 (list prompt (push "title" menu)))
1551 (defun yas-ido-prompt (prompt choices &optional display-fn)
1552 (when (and (fboundp 'ido-completing-read)
1553 (or (>= emacs-major-version 24)
1555 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1557 (eval-when-compile (require 'dropdown-list nil t))
1558 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1559 (when (featurep 'dropdown-list)
1560 (let (formatted-choices
1564 (dolist (choice choices)
1565 (setq d (or (and display-fn (funcall display-fn choice))
1568 (push d formatted-choices)
1569 (push choice filtered-choices)))
1571 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1573 (nth n filtered-choices)
1576 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1577 (let (formatted-choices
1581 (completion-fn (or completion-fn
1582 #'completing-read)))
1583 (dolist (choice choices)
1584 (setq d (or (and display-fn (funcall display-fn choice))
1587 (push d formatted-choices)
1588 (push choice filtered-choices)))
1589 (setq chosen (and formatted-choices
1590 (funcall completion-fn prompt
1596 (let ((position (or (and chosen
1597 (position chosen formatted-choices :test #'string=))
1599 (nth position filtered-choices))))
1601 (defun yas-no-prompt (prompt choices &optional display-fn)
1604 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1605 ;; Loading snippets from files
1607 (defun yas--load-yas-setup-file (file)
1608 (load file 'noerror))
1610 (defun yas-load-directory (top-level-dir &optional use-jit)
1611 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1613 Below TOP-LEVEL-DIR each directory should be a mode name.
1615 Optional USE-JIT use jit-loading of snippets."
1616 (interactive "DSelect the root directory: ")
1617 (unless yas-snippet-dirs
1618 (setq yas-snippet-dirs top-level-dir))
1619 (dolist (dir (yas--subdirs top-level-dir))
1620 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1621 (concat dir "/dummy")))
1622 (mode-sym (car major-mode-and-parents))
1623 (parents (cdr major-mode-and-parents)))
1624 ;; Attention: The parents and the menus are already defined
1625 ;; here, even if the snippets are later jit-loaded.
1627 ;; * We need to know the parents at this point since entering a
1628 ;; given mode should jit load for its parents
1629 ;; immediately. This could be reviewed, the parents could be
1630 ;; discovered just-in-time-as well
1632 ;; * We need to create the menus here to support the `full'
1633 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1635 (yas--define-parents mode-sym parents)
1636 (yas--menu-keymap-get-create mode-sym)
1637 (let ((form `(yas--load-directory-1 ,dir
1641 (not (some #'(lambda (buffer)
1642 (with-current-buffer buffer
1643 (when (eq major-mode mode-sym)
1644 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1647 (yas--schedule-jit mode-sym form)
1649 (when (interactive-p)
1650 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1652 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1653 "Recursively load snippet templates from DIRECTORY."
1654 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1655 (if (and (not no-compiled-snippets)
1656 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1657 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1658 (yas--message 2 "Loading snippet files from %s" directory)
1659 (yas--load-directory-2 directory mode-sym))))
1661 (defun yas--load-directory-2 (directory mode-sym)
1662 ;; Load .yas-setup.el files wherever we find them
1664 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1665 (let* ((default-directory directory)
1667 ;; load the snippet files
1670 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1671 (when (file-readable-p file)
1672 (insert-file-contents file nil nil nil t)
1673 (push (yas--parse-template file)
1676 (yas-define-snippets mode-sym
1678 ;; now recurse to a lower level
1680 (dolist (subdir (yas--subdirs directory))
1681 (yas--load-directory-2 subdir
1684 (defun yas--load-snippet-dirs (&optional nojit)
1685 "Reload the directories listed in `yas-snippet-dirs' or
1686 prompt the user to select one."
1688 (if yas-snippet-dirs
1689 (dolist (directory (reverse (yas-snippet-dirs)))
1690 (cond ((file-directory-p directory)
1691 (yas-load-directory directory (not nojit))
1693 (yas--message 3 "Loaded %s" directory)
1694 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1696 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1697 (call-interactively 'yas-load-directory))
1700 (defun yas-reload-all (&optional interactive)
1701 "Reload all snippets and rebuild the YASnippet menu.
1703 When called interactively force immediate reload of all known
1704 snippets under `yas-snippet-dirs', otherwise use just-in-time
1709 (snippet-editing-buffers
1710 (remove-if-not #'(lambda (buffer)
1711 (with-current-buffer buffer yas--editing-template))
1713 ;; Warn if there are buffers visiting snippets, since reloading will break
1714 ;; any on-line editing of those buffers.
1716 (when snippet-editing-buffers
1718 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1719 (mapc #'kill-buffer snippet-editing-buffers)
1720 (yas--message 1 "Aborted reload...")
1722 ;; in a non-interactive use, at least set
1723 ;; `yas--editing-template' to nil, make it guess it next time around
1724 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1726 ;; Empty all snippet tables, parenting info and all menu tables
1728 (setq yas--tables (make-hash-table))
1729 (setq yas--parents (make-hash-table))
1730 (setq yas--menu-table (make-hash-table))
1732 ;; Cancel all pending 'yas--scheduled-jit-loads'
1734 (setq yas--scheduled-jit-loads (make-hash-table))
1736 ;; Init the `yas-minor-mode-map', taking care not to break the
1739 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1741 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1742 ;; the user to select one.
1744 (setq errors (yas--load-snippet-dirs interactive))
1745 ;; Reload the direct keybindings
1747 (yas-direct-keymaps-reload)
1749 (yas--message 3 "Reloaded everything%s...%s."
1750 (if interactive "" " (snippets will load just-in-time)")
1751 (if errors " (some errors, check *Messages*)" "")))))
1753 (defun yas--load-pending-jits ()
1754 (dolist (mode (yas--modes-to-activate))
1755 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1756 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1757 (dolist (form forms)
1758 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1760 (remhash mode yas--scheduled-jit-loads))))
1762 ;; (when (<= emacs-major-version 22)
1763 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1765 (defun yas--quote-string (string)
1766 "Escape and quote STRING.
1767 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1769 (replace-regexp-in-string "[\\\"]"
1774 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1775 ;;; Snippet compilation function
1777 (defun yas--initialize ()
1778 "For backward compatibility, enable `yas-minor-mode' globally."
1779 (yas-global-mode 1))
1781 (defun yas-compile-directory (top-level-dir)
1782 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1784 This works by stubbing a few functions, then calling
1785 `yas-load-directory'."
1786 (interactive "DTop level snippet directory?")
1787 (cl-flet ((yas--load-yas-setup-file
1789 (let ((elfile (concat file ".el")))
1790 (when (file-exists-p elfile)
1791 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1792 (insert-file-contents elfile)
1793 (goto-char (point-max))
1795 (yas-define-snippets
1797 (insert ";;; Snippet definitions:\n;;;\n")
1798 (let ((literal-snippets (list))
1800 (dolist (snippet snippets)
1801 (let ((key (first snippet))
1802 (template-content (second snippet))
1803 (name (third snippet))
1804 (condition (fourth snippet))
1805 (group (fifth snippet))
1806 (expand-env (sixth snippet))
1807 (file nil) ;; (seventh snippet)) ;; omit on purpose
1808 (binding (eighth snippet))
1809 (uuid (ninth snippet)))
1820 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1822 (yas--load-directory-1
1823 (dir mode parents &rest ignore)
1824 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1825 (with-temp-file output-file
1826 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1827 (yas--load-directory-2 dir mode)
1828 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1829 (yas-load-directory top-level-dir nil)))
1831 (defun yas-recompile-all ()
1832 "Compile every dir in `yas-snippet-dirs'."
1834 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1840 (defvar yas--scheduled-jit-loads (make-hash-table)
1841 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1843 (defun yas--schedule-jit (mode form)
1846 (gethash mode yas--scheduled-jit-loads))
1847 yas--scheduled-jit-loads))
1850 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1851 ;;; Some user level functions
1856 (message (concat "yasnippet (version "
1858 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1860 (defun yas--define-parents (mode parents)
1861 "Add PARENTS to the list of MODE's parents."
1862 (puthash mode (remove-duplicates
1864 (gethash mode yas--parents)))
1867 (defun yas-define-snippets (mode snippets)
1868 "Define SNIPPETS for MODE.
1870 SNIPPETS is a list of snippet definitions, each taking the
1873 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1875 Within these, only KEY and TEMPLATE are actually mandatory.
1877 TEMPLATE might be a lisp form or a string, depending on whether
1878 this is a snippet or a snippet-command.
1880 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1881 been `yas--read-lisp'-ed and will eventually be
1882 `yas--eval-lisp'-ed.
1884 The remaining elements are strings.
1886 FILE is probably of very little use if you're programatically
1889 UUID is the snippets \"unique-id\". Loading a second snippet file
1890 with the same uuid replaced the previous snippet.
1892 You can use `yas--parse-template' to return such lists based on
1893 the current buffers contents."
1894 (let ((snippet-table (yas--table-get-create mode))
1896 (dolist (snippet snippets)
1897 (setq template (yas-define-snippets-1 snippet
1901 (defun yas-define-snippets-1 (snippet snippet-table)
1902 "Helper for `yas-define-snippets'."
1903 ;; X) Calculate some more defaults on the values returned by
1904 ;; `yas--parse-template'.
1906 (let* ((file (seventh snippet))
1908 (name (or (third snippet)
1910 (file-name-directory file))))
1911 (condition (fourth snippet))
1912 (group (fifth snippet))
1913 (keybinding (yas--read-keybinding (eighth snippet)))
1914 (uuid (or (ninth snippet)
1916 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1917 (yas--make-blank-template))))
1918 ;; X) populate the template object
1920 (yas--populate-template template
1921 :table snippet-table
1923 :content (second snippet)
1926 :condition condition
1927 :expand-env (sixth snippet)
1928 :file (seventh snippet)
1929 :keybinding keybinding
1931 ;; X) Update this template in the appropriate table. This step
1932 ;; also will take care of adding the key indicators in the
1933 ;; templates menu entry, if any
1935 (yas--update-template snippet-table template)
1936 ;; X) Return the template
1942 ;;; Apropos snippet menu:
1944 ;; The snippet menu keymaps are store by mode in hash table called
1945 ;; `yas--menu-table'. They are linked to the main menu in
1946 ;; `yas--menu-keymap-get-create' and are initially created empty,
1947 ;; reflecting the table hierarchy.
1949 ;; They can be populated in two mutually exclusive ways: (1) by
1950 ;; reading `yas--template-group', which in turn is populated by the "#
1951 ;; group:" directives of the snippets or the ".yas-make-groups" file
1952 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1953 ;; menu structure based on snippets uuids.
1955 ;; Both situations are handled in `yas--update-template-menu', which
1956 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1957 ;; that can tell between the two situations.
1961 ;; * if `yas-define-menu' is used it must run before
1962 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1963 ;; duplicate entries. The `yas--template' objects are created in
1964 ;; `yas-define-menu', holding nothing but the menu entry,
1965 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1966 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1967 ;; part is then stored in the menu keymap itself which make the item
1968 ;; appear to the user. These limitations could probably be revised.
1970 ;; * The `yas--template-perm-group' slot is only used in
1971 ;; `yas-describe-tables'.
1973 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1974 "Get TEMPLATE's menu binding or assign it a new one.
1976 TYPE may be `:stay', signaling this menu binding should be
1977 static in the menu."
1978 (or (yas--template-menu-binding-pair template)
1979 (let ((key (yas--template-key template))
1980 (keybinding (yas--template-keybinding template)))
1981 (setf (yas--template-menu-binding-pair template)
1982 (cons `(menu-item ,(or (yas--template-name template)
1983 (yas--template-uuid template))
1984 ,(yas--make-menu-binding template)
1987 (defun yas--template-menu-managed-by-yas-define-menu (template)
1988 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
1989 (cdr (yas--template-menu-binding-pair template)))
1992 (defun yas--show-menu-p (mode)
1993 (cond ((eq yas-use-menu 'abbreviate)
1995 (mapcar #'(lambda (table)
1996 (yas--table-mode table))
1997 (yas--get-snippet-tables))))
1998 ((eq yas-use-menu 'full)
2000 ((eq yas-use-menu t)
2003 (defun yas--delete-from-keymap (keymap uuid)
2004 "Recursively delete items with UUID from KEYMAP and its submenus."
2006 ;; XXX: This used to skip any submenus named \"parent mode\"
2008 ;; First of all, recursively enter submenus, i.e. the tree is
2009 ;; searched depth first so that stale submenus can be found in the
2012 (mapc #'(lambda (item)
2013 (when (and (listp (cdr item))
2014 (keymapp (third (cdr item))))
2015 (yas--delete-from-keymap (third (cdr item)) uuid)))
2017 ;; Set the uuid entry to nil
2019 (define-key keymap (vector (make-symbol uuid)) nil)
2020 ;; Destructively modify keymap
2022 (setcdr keymap (delete-if #'(lambda (item)
2023 (or (null (cdr item))
2024 (and (keymapp (third (cdr item)))
2025 (null (cdr (third (cdr item)))))))
2028 (defun yas-define-menu (mode menu &optional omit-items)
2029 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2031 MENU is a list, its elements can be:
2033 - (yas-item UUID) : Creates an entry the snippet identified with
2034 UUID. The menu entry for a snippet thus identified is
2035 permanent, i.e. it will never move (be reordered) in the menu.
2037 - (yas-separator) : Creates a separator
2039 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2040 SUBMENU has the same form as MENU. NAME is also added to the
2041 list of groups of the snippets defined thereafter.
2043 OMIT-ITEMS is a list of snippet uuid's that will always be
2044 omitted from MODE's menu, even if they're manually loaded.
2046 This function does nothing if `yas-use-menu' is nil."
2048 (let* ((table (yas--table-get-create mode))
2049 (hash (yas--table-uuidhash table)))
2050 (yas--define-menu-1 table
2051 (yas--menu-keymap-get-create mode)
2054 (dolist (uuid omit-items)
2055 (let ((template (or (gethash uuid hash)
2056 (yas--populate-template (puthash uuid
2057 (yas--make-blank-template)
2061 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2063 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2064 "Helper for `yas-define-menu'."
2065 (dolist (e (reverse menu))
2066 (cond ((eq (first e) 'yas-item)
2067 (let ((template (or (gethash (second e) uuidhash)
2068 (yas--populate-template (puthash (second e)
2069 (yas--make-blank-template)
2072 :perm-group group-list
2073 :uuid (second e)))))
2074 (define-key menu-keymap (vector (gensym))
2075 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2076 ((eq (first e) 'yas-submenu)
2077 (let ((subkeymap (make-sparse-keymap)))
2078 (define-key menu-keymap (vector (gensym))
2079 `(menu-item ,(second e) ,subkeymap))
2080 (yas--define-menu-1 table
2084 (append group-list (list (second e))))))
2085 ((eq (first e) 'yas-separator)
2086 (define-key menu-keymap (vector (gensym))
2087 '(menu-item "----")))
2089 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2091 (defun yas--define (mode key template &optional name condition group)
2092 "Define a snippet. Expanding KEY into TEMPLATE.
2094 NAME is a description to this template. Also update the menu if
2095 `yas-use-menu' is t. CONDITION is the condition attached to
2096 this snippet. If you attach a condition to a snippet, then it
2097 will only be expanded when the condition evaluated to non-nil."
2098 (yas-define-snippets mode
2099 (list (list key template name condition group))))
2101 (defun yas-hippie-try-expand (first-time?)
2102 "Integrate with hippie expand.
2104 Just put this function in `hippie-expand-try-functions-list'."
2105 (when yas-minor-mode
2106 (if (not first-time?)
2107 (let ((yas-fallback-behavior 'return-nil))
2113 ;;; Apropos condition-cache:
2118 (defvar yas--condition-cache-timestamp nil)
2119 (defmacro yas-define-condition-cache (func doc &rest body)
2120 "Define a function FUNC with doc DOC and body BODY, BODY is
2121 executed at most once every snippet expansion attempt, to check
2122 expansion conditions.
2124 It doesn't make any sense to call FUNC programatically."
2125 `(defun ,func () ,(if (and doc
2128 "\n\nFor use in snippets' conditions. Within each
2129 snippet-expansion routine like `yas-expand', computes actual
2130 value for the first time then always returns a cached value.")
2131 (setq body (cons doc body))
2133 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2134 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2135 (cdr timestamp-and-value)
2136 (let ((new-value (progn
2139 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2142 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2143 (defun yas-expand-from-trigger-key (&optional field)
2144 "Expand a snippet before point.
2146 If no snippet expansion is possible, fall back to the behaviour
2147 defined in `yas-fallback-behavior'.
2149 Optional argument FIELD is for non-interactive use and is an
2150 object satisfying `yas--field-p' to restrict the expansion to."
2152 (setq yas--condition-cache-timestamp (current-time))
2153 (let (templates-and-pos)
2154 (unless (and yas-expand-only-for-last-commands
2155 (not (member last-command yas-expand-only-for-last-commands)))
2156 (setq templates-and-pos (if field
2158 (narrow-to-region (yas--field-start field)
2159 (yas--field-end field))
2161 (yas--current-key))))
2162 (if (and templates-and-pos
2163 (first templates-and-pos))
2164 (yas--expand-or-prompt-for-template (first templates-and-pos)
2165 (second templates-and-pos)
2166 (third templates-and-pos))
2167 (yas--fallback 'trigger-key))))
2169 (defun yas-expand-from-keymap ()
2170 "Directly expand some snippets, searching `yas--direct-keymaps'.
2172 If expansion fails, execute the previous binding for this key"
2174 (setq yas--condition-cache-timestamp (current-time))
2175 (let* ((yas--prefix current-prefix-arg)
2176 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2177 universal-argument-num-events
2179 (templates (mapcan #'(lambda (table)
2180 (yas--fetch table vec))
2181 (yas--get-snippet-tables))))
2183 (yas--expand-or-prompt-for-template templates)
2184 (let ((yas-fallback-behavior 'call-other-command))
2187 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2188 "Expand one of TEMPLATES from START to END.
2190 Prompt the user if TEMPLATES has more than one element, else
2191 expand immediately. Common gateway for
2192 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2193 (let ((yas--current-template (or (and (rest templates) ;; more than one
2194 (yas--prompt-for-template (mapcar #'cdr templates)))
2196 (when yas--current-template
2197 (yas-expand-snippet (yas--template-content yas--current-template)
2200 (yas--template-expand-env yas--current-template)))))
2202 ;; Apropos the trigger key and the fallback binding:
2204 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2205 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2206 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2207 ;; improve this explanation.
2209 (defun yas--fallback (&optional from-trigger-key-p)
2210 "Fallback after expansion has failed.
2212 Common gateway for `yas-expand-from-trigger-key' and
2213 `yas-expand-from-keymap'."
2214 (cond ((eq yas-fallback-behavior 'return-nil)
2217 ((eq yas-fallback-behavior 'call-other-command)
2218 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2219 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2220 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2221 (setq this-original-command beyond-yasnippet)
2222 (call-interactively beyond-yasnippet)))
2223 ((and (listp yas-fallback-behavior)
2224 (cdr yas-fallback-behavior)
2225 (eq 'apply (car yas-fallback-behavior)))
2226 (if (cddr yas-fallback-behavior)
2227 (apply (cadr yas-fallback-behavior)
2228 (cddr yas-fallback-behavior))
2229 (when (commandp (cadr yas-fallback-behavior))
2230 (setq this-command (cadr yas-fallback-behavior))
2231 (call-interactively (cadr yas-fallback-behavior)))))
2233 ;; also return nil if all the other fallbacks have failed
2236 (defun yas--keybinding-beyond-yasnippet ()
2238 (let* ((yas-minor-mode nil)
2239 (yas--direct-keymaps nil)
2240 (keys (this-single-command-keys)))
2241 (or (key-binding keys t)
2242 (key-binding (yas--fallback-translate-input keys) t))))
2244 (defun yas--fallback-translate-input (keys)
2245 "Emulate `read-key-sequence', at least what I think it does.
2247 Keys should be an untranslated key vector. Returns a translated
2248 vector of keys. FIXME not thoroughly tested"
2251 (while (< i (length keys))
2253 (translated local-function-key-map))
2254 (while (and (< j (length keys))
2256 (keymapp translated))
2257 (setq translated (aget (remove 'keymap translated) (aref keys j))
2259 (setq retval (vconcat retval (cond ((symbolp translated)
2261 ((vectorp translated)
2264 (substring keys i j)))))
2269 ;;; Utils for snippet development:
2271 (defun yas--all-templates (tables)
2272 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2274 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2275 `yas-buffer-local-condition'"
2276 (when yas-choose-tables-first
2277 (setq tables (list (yas--prompt-for-table tables))))
2279 (if yas-choose-keys-first
2280 (let ((key (yas--prompt-for-keys
2281 (mapcan #'yas--table-all-keys tables))))
2283 (mapcan #'(lambda (table)
2284 (yas--fetch table key))
2286 (remove-duplicates (mapcan #'yas--table-templates tables)
2289 (defun yas-insert-snippet (&optional no-condition)
2290 "Choose a snippet to expand, pop-up a list of choices according
2291 to `yas--prompt-function'.
2293 With prefix argument NO-CONDITION, bypass filtering of snippets
2296 (setq yas--condition-cache-timestamp (current-time))
2297 (let* ((yas-buffer-local-condition (or (and no-condition
2299 yas-buffer-local-condition))
2300 (templates (yas--all-templates (yas--get-snippet-tables)))
2301 (yas--current-template (and templates
2302 (or (and (rest templates) ;; more than one template for same key
2303 (yas--prompt-for-template templates))
2305 (where (if (region-active-p)
2306 (cons (region-beginning) (region-end))
2307 (cons (point) (point)))))
2308 (if yas--current-template
2309 (yas-expand-snippet (yas--template-content yas--current-template)
2312 (yas--template-expand-env yas--current-template))
2313 (yas--message 3 "No snippets can be inserted here!"))))
2315 (defun yas-visit-snippet-file ()
2316 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2318 Only success if selected snippet was loaded from a file. Put the
2319 visited file in `snippet-mode'."
2321 (let* ((yas-buffer-local-condition 'always)
2322 (templates (yas--all-templates (yas--get-snippet-tables)))
2323 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2324 (template (and templates
2325 (or (yas--prompt-for-template templates
2326 "Choose a snippet template to edit: ")
2330 (yas--visit-snippet-file-1 template)
2331 (message "No snippets tables active!"))))
2333 (defun yas--visit-snippet-file-1 (template)
2334 "Helper for `yas-visit-snippet-file'."
2335 (let ((file (yas--template-file template)))
2336 (cond ((and file (file-readable-p file))
2337 (find-file-other-window file)
2339 (set (make-local-variable 'yas--editing-template) template))
2341 (message "Original file %s no longer exists!" file))
2343 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2344 (let ((type 'snippet))
2345 (when (listp (yas--template-content template))
2346 (insert (format "# type: command\n"))
2347 (setq type 'command))
2348 (insert (format "# key: %s\n" (yas--template-key template)))
2349 (insert (format "# name: %s\n" (yas--template-name template)))
2350 (when (yas--template-keybinding template)
2351 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2352 (when (yas--template-expand-env template)
2353 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2354 (when (yas--template-condition template)
2355 (insert (format "# condition: %s\n" (yas--template-condition template))))
2357 (insert (if (eq type 'command)
2358 (pp-to-string (yas--template-content template))
2359 (yas--template-content template))))
2361 (set (make-local-variable 'yas--editing-template) template)))))
2363 (defun yas--guess-snippet-directories-1 (table)
2364 "Guesses possible snippet subdirectories for TABLE."
2365 (cons (yas--table-name table)
2366 (mapcan #'(lambda (parent)
2367 (yas--guess-snippet-directories-1
2369 (yas--table-parents table))))
2371 (defun yas--guess-snippet-directories (&optional table)
2372 "Try to guess suitable directories based on the current active
2373 tables (or optional TABLE).
2375 Returns a list of elements (TABLE . DIRS) where TABLE is a
2376 `yas--table' object and DIRS is a list of all possible directories
2377 where snippets of table might exist."
2378 (let ((main-dir (replace-regexp-in-string
2380 (or (first (or (yas-snippet-dirs)
2381 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2382 (tables (or (and table
2384 (yas--get-snippet-tables))))
2385 ;; HACK! the snippet table created here is actually registered!
2387 (unless (or table (gethash major-mode yas--tables))
2388 (push (yas--table-get-create major-mode)
2391 (mapcar #'(lambda (table)
2393 (mapcar #'(lambda (subdir)
2394 (concat main-dir "/" subdir))
2395 (yas--guess-snippet-directories-1 table))))
2398 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2399 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2400 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2401 (let ((candidate (first (cdr table-and-dirs))))
2402 (unless (file-writable-p (file-name-directory candidate))
2403 (error (yas--format "%s is not writable." candidate)))
2404 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2406 (if (gethash (yas--table-mode (car table-and-dirs))
2410 (or main-table-string
2412 (yas--table-name (car table-and-dirs))))
2414 (make-directory candidate 'also-make-parents)
2415 ;; create the .yas-parents file here...
2418 (defun yas-new-snippet (&optional no-template)
2419 "Pops a new buffer for writing a snippet.
2421 Expands a snippet-writing snippet, unless the optional prefix arg
2422 NO-TEMPLATE is non-nil."
2424 (let ((guessed-directories (yas--guess-snippet-directories)))
2426 (switch-to-buffer "*new snippet*")
2428 (kill-all-local-variables)
2431 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2432 (yas--table-mode (car d)))
2433 guessed-directories))
2434 (unless no-template (yas-expand-snippet "\
2435 # -*- mode: snippet -*-
2437 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2438 # binding: ${4:direct-keybinding}}${5:
2439 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2444 (defun yas--compute-major-mode-and-parents (file)
2445 "Given FILE, find the nearest snippet directory for a given mode.
2447 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2448 representing one or more of the mode's parents.
2450 Note that MODE-SYM need not be the symbol of a real major mode,
2451 neither do the elements of PARENTS."
2452 (let* ((file-dir (and file
2453 (directory-file-name (or (some #'(lambda (special)
2454 (locate-dominating-file file special))
2458 (directory-file-name (file-name-directory file))))))
2459 (parents-file-name (concat file-dir "/.yas-parents"))
2460 (major-mode-name (and file-dir
2461 (file-name-nondirectory file-dir)))
2462 (major-mode-sym (or (and major-mode-name
2463 (intern major-mode-name))))
2464 (parents (when (file-readable-p parents-file-name)
2468 (insert-file-contents parents-file-name)
2469 (buffer-substring-no-properties (point-min)
2471 (when major-mode-sym
2472 (cons major-mode-sym parents))))
2474 (defvar yas--editing-template nil
2475 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2477 (defvar yas--current-template nil
2478 "Holds the current template being expanded into a snippet.")
2480 (defvar yas--guessed-modes nil
2481 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2483 (defun yas--read-table ()
2484 "Ask user for a snippet table, help with some guessing."
2485 (let ((prompt (if (and (featurep 'ido)
2487 'ido-completing-read 'completing-read)))
2488 (unless yas--guessed-modes
2489 (set (make-local-variable 'yas--guessed-modes)
2490 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2492 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2493 (if yas--guessed-modes
2494 (first yas--guessed-modes)
2496 (mapcar #'symbol-name yas--guessed-modes)
2501 (if (first yas--guessed-modes)
2502 (symbol-name (first yas--guessed-modes)))))))
2504 (defun yas-load-snippet-buffer (table &optional interactive)
2505 "Parse and load current buffer's snippet definition into TABLE.
2507 TABLE is a symbol naming a passed to `yas--table-get-create'.
2509 When called interactively, prompt for the table name and
2510 whether (and where) to save the snippet, then quit the window."
2511 (interactive (list (yas--read-table) t))
2513 ;; We have `yas--editing-template', this buffer's content comes from a
2514 ;; template which is already loaded and neatly positioned,...
2516 (yas--editing-template
2517 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2518 (yas--template-table yas--editing-template)))
2519 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2520 ;; value from `yas--compute-major-mode-and-parents'
2523 (unless yas--guessed-modes
2524 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2525 (let* ((table (yas--table-get-create table)))
2526 (set (make-local-variable 'yas--editing-template)
2527 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2530 (when (and interactive
2532 ;; Only offer to save this if it looks like a library or new
2533 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2534 ;; which is not the first, or from an unwritable file)
2536 (not (yas--template-file yas--editing-template))
2537 (not (file-writable-p (yas--template-file yas--editing-template)))
2538 (and (listp yas-snippet-dirs)
2539 (second yas-snippet-dirs)
2540 (not (string-match (expand-file-name (first yas-snippet-dirs))
2541 (yas--template-file yas--editing-template)))))
2542 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2543 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2545 (yas--make-directory-maybe option))))
2547 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2548 (file-name-nondirectory (yas--template-file yas--editing-template)))
2549 (yas--template-name yas--editing-template))))
2550 (write-file (concat chosen "/"
2551 (read-from-minibuffer (format "File name to create in %s? " chosen)
2552 default-file-name)))
2553 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2555 (yas--message 3 "Snippet \"%s\" loaded for %s."
2556 (yas--template-name yas--editing-template)
2557 (yas--table-name (yas--template-table yas--editing-template)))
2558 (quit-window interactive)))
2560 (defun yas-tryout-snippet (&optional debug)
2561 "Test current buffer's snippet template in other buffer."
2563 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2564 (parsed (yas--parse-template))
2565 (test-mode (or (and (car major-mode-and-parent)
2566 (fboundp (car major-mode-and-parent))
2567 (car major-mode-and-parent))
2568 (first yas--guessed-modes)
2569 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2570 (yas--current-template
2573 (yas--populate-template (yas--make-blank-template)
2574 :table nil ;; no tables for ephemeral snippets
2576 :content (second parsed)
2577 :name (third parsed)
2578 :expand-env (sixth parsed)))))
2579 (cond (yas--current-template
2580 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2581 (kill-buffer (get-buffer-create buffer-name))
2582 (switch-to-buffer (get-buffer-create buffer-name))
2583 (setq buffer-undo-list nil)
2584 (condition-case nil (funcall test-mode) (error nil))
2586 (setq buffer-read-only nil)
2587 (yas-expand-snippet (yas--template-content yas--current-template)
2590 (yas--template-expand-env yas--current-template))
2592 (require 'yasnippet-debug nil t))
2593 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2595 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2597 (defun yas-active-keys ()
2598 "Return all active trigger keys for current buffer and point."
2599 (remove-duplicates (mapcan #'yas--table-all-keys (yas--get-snippet-tables))
2602 (defun yas--template-fine-group (template)
2603 (car (last (or (yas--template-group template)
2604 (yas--template-perm-group template)))))
2606 (defun yas-describe-tables (&optional choose)
2607 "Display snippets for each table."
2609 (let* ((by-name-hash (and choose
2610 (y-or-n-p "Show by namehash? ")))
2611 (buffer (get-buffer-create "*YASnippet tables*"))
2612 (active-tables (yas--get-snippet-tables))
2613 (remain-tables (let ((all))
2614 (maphash #'(lambda (k v)
2615 (unless (find v active-tables)
2619 (table-lists (list active-tables remain-tables))
2620 (original-buffer (current-buffer))
2622 (yas--condition-cache-timestamp (current-time)))
2623 (with-current-buffer buffer
2624 (setq buffer-read-only nil)
2626 (cond ((not by-name-hash)
2627 (insert "YASnippet tables: \n")
2628 (while (and table-lists
2630 (dolist (table (car table-lists))
2631 (yas--describe-pretty-table table original-buffer))
2632 (setq table-lists (cdr table-lists))
2634 (yas--create-snippet-xrefs)
2635 (display-buffer buffer)
2636 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2637 (yas--create-snippet-xrefs)
2641 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2642 (dolist (table (append active-tables remain-tables))
2643 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2645 (maphash #'(lambda (k v)
2647 (yas--table-hash table))
2649 (insert (format " key %s maps snippets: %s\n" key
2651 (maphash #'(lambda (k v)
2653 (gethash key (yas--table-hash table)))
2656 (setq buffer-read-only t))
2657 (display-buffer buffer)))
2659 (defun yas--describe-pretty-table (table &optional original-buffer)
2660 (insert (format "\nSnippet table `%s'"
2661 (yas--table-name table)))
2662 (if (yas--table-parents table)
2663 (insert (format " parents: %s\n"
2664 (mapcar #'yas--table-name
2665 (yas--table-parents table))))
2667 (insert (make-string 100 ?-) "\n")
2668 (insert "group state name key binding\n")
2669 (let ((groups-hash (make-hash-table :test #'equal)))
2670 (maphash #'(lambda (k v)
2671 (let ((group (or (yas--template-fine-group v)
2673 (when (yas--template-name v)
2675 (cons v (gethash group groups-hash))
2677 (yas--table-uuidhash table))
2679 #'(lambda (group templates)
2680 (setq group (truncate-string-to-width group 25 0 ? "..."))
2681 (insert (make-string 100 ?-) "\n")
2682 (dolist (p templates)
2683 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2687 (setq group (make-string (length group) ? ))))
2688 (condition-string (let ((condition (yas--template-condition p)))
2691 (with-current-buffer original-buffer
2692 (if (yas--eval-condition condition)
2697 (insert condition-string " ")
2699 (if (string-match "\\.\\.\\.$" name)
2703 (insert (truncate-string-to-width (or (yas--template-key p) "")
2705 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2712 ;;; User convenience functions, for using in snippet definitions
2714 (defvar yas-modified-p nil
2715 "Non-nil if field has been modified by user or transformation.")
2717 (defvar yas-moving-away-p nil
2718 "Non-nil if user is about to exit field.")
2720 (defvar yas-text nil
2721 "Contains current field text.")
2723 (defun yas-substr (str pattern &optional subexp)
2724 "Search PATTERN in STR and return SUBEXPth match.
2726 If found, the content of subexp group SUBEXP (default 0) is
2727 returned, or else the original STR will be returned."
2728 (let ((grp (or subexp 0)))
2730 (if (string-match pattern str)
2731 (match-string-no-properties grp str)
2734 (defun yas-choose-value (&rest possibilities)
2735 "Prompt for a string in POSSIBILITIES and return it.
2737 The last element of POSSIBILITIES may be a list of strings."
2738 (unless (or yas-moving-away-p
2740 (setq possibilities (nreverse possibilities))
2741 (setq possibilities (if (listp (car possibilities))
2742 (append (reverse (car possibilities)) (rest possibilities))
2744 (some #'(lambda (fn)
2745 (funcall fn "Choose: " possibilities))
2746 yas-prompt-functions)))
2748 (defun yas-key-to-value (alist)
2749 (unless (or yas-moving-away-p
2751 (let ((key (read-key-sequence "")))
2753 (or (cdr (find key alist :key #'car :test #'string=))
2756 (defun yas-throw (text)
2757 "Throw a yas--exception with TEXT as the reason."
2758 (throw 'yas--exception (cons 'yas--exception text)))
2760 (defun yas-verify-value (possibilities)
2761 "Verify that the current field value is in POSSIBILITIES.
2763 Otherwise throw exception."
2764 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2765 (yas-throw (yas--format "Field only allows %s" possibilities))))
2767 (defun yas-field-value (number)
2768 "Get the string for field with NUMBER.
2770 Use this in primary and mirror transformations to tget."
2771 (let* ((snippet (car (yas--snippets-at-point)))
2773 (yas--snippet-find-field snippet number))))
2775 (yas--field-text-for-display field))))
2778 "Return `yas-text' if that exists and is non-empty, else nil."
2780 (not (string= "" yas-text)))
2783 (defun yas-selected-text ()
2784 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2785 (if (and yas-selected-text
2786 (not (string= "" yas-selected-text)))
2789 (defun yas--get-field-once (number &optional transform-fn)
2790 (unless yas-modified-p
2792 (funcall transform-fn (yas-field-value number))
2793 (yas-field-value number))))
2795 (defun yas-default-from-field (number)
2796 (unless yas-modified-p
2797 (yas-field-value number)))
2799 (defun yas-inside-string ()
2800 "Return non-nil if the point is inside a string according to font-lock."
2801 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2803 (defun yas-unimplemented (&optional missing-feature)
2804 (if yas--current-template
2805 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2808 (yas--visit-snippet-file-1 yas--current-template))
2809 (message "No implementation. Missing %s" (or missing-feature "something"))))
2812 ;;; Snippet expansion and field management
2814 (defvar yas--active-field-overlay nil
2815 "Overlays the currently active field.")
2817 (defvar yas--field-protection-overlays nil
2818 "Two overlays protect the current active field.")
2820 (defconst yas--prefix nil
2821 "A prefix argument for expansion direct from keybindings.")
2823 (defvar yas-selected-text nil
2824 "The selected region deleted on the last snippet expansion.")
2826 (defvar yas--start-column nil
2827 "The column where the snippet expansion started.")
2829 (make-variable-buffer-local 'yas--active-field-overlay)
2830 (make-variable-buffer-local 'yas--field-protection-overlays)
2831 (put 'yas--active-field-overlay 'permanent-local t)
2832 (put 'yas--field-protection-overlays 'permanent-local t)
2834 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2840 (id (yas--snippet-next-id) :read-only t)
2841 (control-overlay nil)
2843 ;; stacked expansion: the `previous-active-field' slot saves the
2844 ;; active field where the child expansion took place
2845 previous-active-field
2848 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2858 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2865 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2869 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2870 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2872 If there is no transform for ht field, return nil.
2874 If there is a transform but it returns nil, return the empty
2875 string iff EMPTY-ON-NIL-P is true."
2876 (let* ((yas-text (yas--field-text-for-display field))
2878 (yas-modified-p (yas--field-modified-p field))
2879 (yas-moving-away-p nil)
2880 (transform (if (yas--mirror-p field-or-mirror)
2881 (yas--mirror-transform field-or-mirror)
2882 (yas--field-transform field-or-mirror)))
2883 (start-point (if (yas--mirror-p field-or-mirror)
2884 (yas--mirror-start field-or-mirror)
2885 (yas--field-start field-or-mirror)))
2886 (transformed (and transform
2888 (goto-char start-point)
2889 (let ((ret (yas--eval-lisp transform)))
2890 (or ret (and empty-on-nil-p "")))))))
2893 (defsubst yas--replace-all (from to &optional text)
2894 "Replace all occurrences from FROM to TO.
2896 With optional string TEXT do it in that string."
2898 (replace-regexp-in-string (regexp-quote from) to text t t)
2899 (goto-char (point-min))
2900 (while (search-forward from nil t)
2901 (replace-match to t t text))))
2903 (defun yas--snippet-find-field (snippet number)
2904 (find-if #'(lambda (field)
2905 (eq number (yas--field-number field)))
2906 (yas--snippet-fields snippet)))
2908 (defun yas--snippet-sort-fields (snippet)
2909 "Sort the fields of SNIPPET in navigation order."
2910 (setf (yas--snippet-fields snippet)
2911 (sort (yas--snippet-fields snippet)
2912 #'yas--snippet-field-compare)))
2914 (defun yas--snippet-field-compare (field1 field2)
2915 "Compare FIELD1 and FIELD2.
2917 The field with a number is sorted first. If they both have a
2918 number, compare through the number. If neither have, compare
2919 through the field's start point"
2920 (let ((n1 (yas--field-number field1))
2921 (n2 (yas--field-number field2)))
2924 (or (zerop n2) (and (not (zerop n1))
2929 (< (yas--field-start field1)
2930 (yas--field-start field2))))))
2932 (defun yas--field-probably-deleted-p (snippet field)
2933 "Guess if SNIPPET's FIELD should be skipped."
2935 ;; field must be zero length
2937 (zerop (- (yas--field-start field) (yas--field-end field)))
2940 ;; 1) is a nested field and it's been modified
2942 (and (yas--field-parent-field field)
2943 (yas--field-modified-p field))
2944 ;; 2) ends just before the snippet end
2946 (and (eq field (car (last (yas--snippet-fields snippet))))
2947 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2948 ;; the field numbered 0, just before the exit marker, should
2951 (not (zerop (yas--field-number field)))))
2953 (defun yas--snippets-at-point (&optional all-snippets)
2954 "Return a sorted list of snippets at point.
2956 The most recently-inserted snippets are returned first."
2958 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2959 (overlay-get ov 'yas--snippet))
2961 (overlays-in (point-min) (point-max))
2962 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2964 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2966 (defun yas-next-field-or-maybe-expand ()
2967 "Try to expand a snippet at a key before point.
2969 Otherwise delegate to `yas-next-field'."
2971 (if yas-triggers-in-field
2972 (let ((yas-fallback-behavior 'return-nil)
2973 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2975 (unless (yas-expand-from-trigger-key active-field)
2979 (defun yas-next-field (&optional arg)
2980 "Navigate to the ARGth next field.
2982 If there's none, exit the snippet."
2986 (snippet (first (yas--snippets-at-point)))
2987 (active-field (overlay-get yas--active-field-overlay 'yas--field))
2988 (live-fields (remove-if #'(lambda (field)
2989 (and (not (eq field active-field))
2990 (yas--field-probably-deleted-p snippet field)))
2991 (yas--snippet-fields snippet)))
2992 (active-field-pos (position active-field live-fields))
2993 (target-pos (and active-field-pos (+ arg active-field-pos)))
2994 (target-field (and target-pos (nth target-pos live-fields))))
2995 ;; First check if we're moving out of a field with a transform
2997 (when (and active-field
2998 (yas--field-transform active-field))
2999 (let* ((yas-moving-away-p t)
3000 (yas-text (yas--field-text-for-display active-field))
3002 (yas-modified-p (yas--field-modified-p active-field)))
3003 ;; primary field transform: exit call to field-transform
3004 (yas--eval-lisp (yas--field-transform active-field))))
3005 ;; Now actually move...
3006 (cond ((and target-pos (>= target-pos (length live-fields)))
3007 (yas-exit-snippet snippet))
3009 (yas--move-to-field snippet target-field))
3013 (defun yas--place-overlays (snippet field)
3014 "Correctly place overlays for SNIPPET's FIELD."
3015 (yas--make-move-field-protection-overlays snippet field)
3016 (yas--make-move-active-field-overlay snippet field))
3018 (defun yas--move-to-field (snippet field)
3019 "Update SNIPPET to move to field FIELD.
3021 Also create some protection overlays"
3022 (goto-char (yas--field-start field))
3023 (yas--place-overlays snippet field)
3024 (overlay-put yas--active-field-overlay 'yas--field field)
3025 (let ((number (yas--field-number field)))
3026 ;; check for the special ${0: ...} field
3027 (if (and number (zerop number))
3029 (set-mark (yas--field-end field))
3030 (setf (yas--snippet-force-exit snippet)
3031 (or (yas--field-transform field)
3033 ;; make this field active
3034 (setf (yas--snippet-active-field snippet) field)
3035 ;; primary field transform: first call to snippet transform
3036 (unless (yas--field-modified-p field)
3037 (if (yas--field-update-display field snippet)
3038 (yas--update-mirrors snippet)
3039 (setf (yas--field-modified-p field) nil))))))
3041 (defun yas-prev-field ()
3042 "Navigate to prev field. If there's none, exit the snippet."
3044 (yas-next-field -1))
3046 (defun yas-abort-snippet (&optional snippet)
3048 (let ((snippet (or snippet
3049 (car (yas--snippets-at-point)))))
3051 (setf (yas--snippet-force-exit snippet) t))))
3053 (defun yas-exit-snippet (snippet)
3054 "Goto exit-marker of SNIPPET."
3055 (interactive (list (first (yas--snippets-at-point))))
3057 (setf (yas--snippet-force-exit snippet) t)
3058 (goto-char (if (yas--snippet-exit snippet)
3059 (yas--exit-marker (yas--snippet-exit snippet))
3060 (overlay-end (yas--snippet-control-overlay snippet))))))
3062 (defun yas-exit-all-snippets ()
3063 "Exit all snippets."
3065 (mapc #'(lambda (snippet)
3066 (yas-exit-snippet snippet)
3067 (yas--check-commit-snippet))
3068 (yas--snippets-at-point 'all-snippets)))
3071 ;;; Some low level snippet-routines:
3073 (defmacro yas--inhibit-overlay-hooks (&rest body)
3074 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3075 (declare (indent 0))
3076 `(let ((yas--inhibit-overlay-hooks t))
3079 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3080 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3082 (defun yas--commit-snippet (snippet)
3083 "Commit SNIPPET, but leave point as it is.
3085 This renders the snippet as ordinary text."
3087 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3089 ;; Save the end of the moribund snippet in case we need to revive it
3090 ;; its original expansion.
3092 (when (and control-overlay
3093 (overlay-buffer control-overlay))
3094 (setq yas-snippet-beg (overlay-start control-overlay))
3095 (setq yas-snippet-end (overlay-end control-overlay))
3096 (delete-overlay control-overlay))
3098 (yas--inhibit-overlay-hooks
3099 (when yas--active-field-overlay
3100 (delete-overlay yas--active-field-overlay))
3101 (when yas--field-protection-overlays
3102 (mapc #'delete-overlay yas--field-protection-overlays)))
3104 ;; stacked expansion: if the original expansion took place from a
3105 ;; field, make sure we advance it here at least to
3106 ;; `yas-snippet-end'...
3108 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3109 (when (and yas-snippet-end previous-field)
3110 (yas--advance-end-maybe previous-field yas-snippet-end)))
3112 ;; Convert all markers to points,
3114 (yas--markers-to-points snippet)
3116 ;; Take care of snippet revival
3118 (if yas-snippet-revival
3119 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3121 ;; Dismember the snippet... this is useful if we get called
3122 ;; again from `yas--take-care-of-redo'....
3123 (setf (yas--snippet-fields snippet) nil)))
3125 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3127 (defun yas--safely-run-hooks (hook-var)
3128 (condition-case error
3129 (run-hooks hook-var)
3131 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3134 (defun yas--check-commit-snippet ()
3135 "Checks if point exited the currently active field of the snippet.
3137 If so cleans up the whole snippet up."
3138 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3139 (snippets-left snippets)
3140 (snippet-exit-transform))
3141 (dolist (snippet snippets)
3142 (let ((active-field (yas--snippet-active-field snippet)))
3143 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3144 (cond ((or snippet-exit-transform
3145 (not (and active-field (yas--field-contains-point-p active-field))))
3146 (setq snippets-left (delete snippet snippets-left))
3147 (setf (yas--snippet-force-exit snippet) nil)
3148 (yas--commit-snippet snippet))
3150 (or (not yas--active-field-overlay)
3151 (not (overlay-buffer yas--active-field-overlay))))
3153 ;; stacked expansion: this case is mainly for recent
3154 ;; snippet exits that place us back int the field of
3158 (yas--move-to-field snippet active-field)
3159 (yas--update-mirrors snippet)))
3162 (unless (or (null snippets) snippets-left)
3163 (if snippet-exit-transform
3164 (yas--eval-lisp-no-saves snippet-exit-transform))
3165 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3167 ;; Apropos markers-to-points:
3169 ;; This was found useful for performance reasons, so that an
3170 ;; excessive number of live markers aren't kept around in the
3171 ;; `buffer-undo-list'. However, in `markers-to-points', the
3172 ;; set-to-nil markers can't simply be discarded and replaced with
3173 ;; fresh ones in `points-to-markers'. The original marker that was
3174 ;; just set to nil has to be reused.
3176 ;; This shouldn't bring horrible problems with undo/redo, but it
3179 (defun yas--markers-to-points (snippet)
3180 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3181 where POINT is the original position of the marker and MARKER is
3182 the original marker object with the position set to nil."
3183 (dolist (field (yas--snippet-fields snippet))
3184 (let ((start (marker-position (yas--field-start field)))
3185 (end (marker-position (yas--field-end field))))
3186 (set-marker (yas--field-start field) nil)
3187 (set-marker (yas--field-end field) nil)
3188 (setf (yas--field-start field) (cons start (yas--field-start field)))
3189 (setf (yas--field-end field) (cons end (yas--field-end field))))
3190 (dolist (mirror (yas--field-mirrors field))
3191 (let ((start (marker-position (yas--mirror-start mirror)))
3192 (end (marker-position (yas--mirror-end mirror))))
3193 (set-marker (yas--mirror-start mirror) nil)
3194 (set-marker (yas--mirror-end mirror) nil)
3195 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3196 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3197 (let ((snippet-exit (yas--snippet-exit snippet)))
3199 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3200 (set-marker (yas--exit-marker snippet-exit) nil)
3201 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3203 (defun yas--points-to-markers (snippet)
3204 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3206 This is done by setting MARKER to POINT with `set-marker'."
3207 (dolist (field (yas--snippet-fields snippet))
3208 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3209 (car (yas--field-start field))))
3210 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3211 (car (yas--field-end field))))
3212 (dolist (mirror (yas--field-mirrors field))
3213 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3214 (car (yas--mirror-start mirror))))
3215 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3216 (car (yas--mirror-end mirror))))))
3217 (let ((snippet-exit (yas--snippet-exit snippet)))
3219 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3220 (car (yas--exit-marker snippet-exit)))))))
3222 (defun yas--field-contains-point-p (field &optional point)
3223 (let ((point (or point
3225 (and (>= point (yas--field-start field))
3226 (<= point (yas--field-end field)))))
3228 (defun yas--field-text-for-display (field)
3229 "Return the propertized display text for field FIELD."
3230 (buffer-substring (yas--field-start field) (yas--field-end field)))
3232 (defun yas--undo-in-progress ()
3233 "True if some kind of undo is in progress."
3234 (or undo-in-progress
3235 (eq this-command 'undo)
3236 (eq this-command 'redo)))
3238 (defun yas--make-control-overlay (snippet start end)
3239 "Creates the control overlay that surrounds the snippet and
3241 (let ((overlay (make-overlay start
3246 (overlay-put overlay 'keymap yas-keymap)
3247 (overlay-put overlay 'priority 100)
3248 (overlay-put overlay 'yas--snippet snippet)
3251 (defun yas-skip-and-clear-or-delete-char (&optional field)
3252 "Clears unmodified field if at field start, skips to next tab.
3254 Otherwise deletes a character normally by calling `delete-char'."
3256 (let ((field (or field
3257 (and yas--active-field-overlay
3258 (overlay-buffer yas--active-field-overlay)
3259 (overlay-get yas--active-field-overlay 'yas--field)))))
3261 (not (yas--field-modified-p field))
3262 (eq (point) (marker-position (yas--field-start field))))
3263 (yas--skip-and-clear field)
3266 (call-interactively 'delete-char)))))
3268 (defun yas--skip-and-clear (field)
3269 "Deletes the region of FIELD and sets it's modified state to t."
3270 ;; Just before skipping-and-clearing the field, mark its children
3271 ;; fields as modified, too. If the children have mirrors-in-fields
3272 ;; this prevents them from updating erroneously (we're skipping and
3275 (yas--mark-this-and-children-modified field)
3276 (delete-region (yas--field-start field) (yas--field-end field)))
3278 (defun yas--mark-this-and-children-modified (field)
3279 (setf (yas--field-modified-p field) t)
3280 (let ((fom (yas--field-next field)))
3282 (yas--fom-parent-field fom))
3283 (when (and (eq (yas--fom-parent-field fom) field)
3285 (yas--mark-this-and-children-modified fom))
3286 (setq fom (yas--fom-next fom)))))
3288 (defun yas--make-move-active-field-overlay (snippet field)
3289 "Place the active field overlay in SNIPPET's FIELD.
3291 Move the overlay, or create it if it does not exit."
3292 (if (and yas--active-field-overlay
3293 (overlay-buffer yas--active-field-overlay))
3294 (move-overlay yas--active-field-overlay
3295 (yas--field-start field)
3296 (yas--field-end field))
3297 (setq yas--active-field-overlay
3298 (make-overlay (yas--field-start field)
3299 (yas--field-end field)
3301 (overlay-put yas--active-field-overlay 'priority 100)
3302 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3303 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3304 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3305 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3306 '(yas--on-field-overlay-modification))
3307 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3308 '(yas--on-field-overlay-modification))))
3310 (defvar yas--inhibit-overlay-hooks nil
3311 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3313 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3314 "Clears the field and updates mirrors, conditionally.
3316 Only clears the field if it hasn't been modified and it point it
3317 at field start. This hook doesn't do anything if an undo is in
3319 (unless (or yas--inhibit-overlay-hooks
3320 (yas--undo-in-progress))
3321 (let* ((field (overlay-get overlay 'yas--field))
3322 (number (and field (yas--field-number field)))
3323 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3325 (yas--advance-end-maybe field (overlay-end overlay))
3327 (yas--field-update-display field snippet))
3328 (yas--update-mirrors snippet))
3330 (when (and (not after?)
3331 (not (yas--field-modified-p field))
3332 (eq (point) (if (markerp (yas--field-start field))
3333 (marker-position (yas--field-start field))
3334 (yas--field-start field))))
3335 (yas--skip-and-clear field))
3336 (setf (yas--field-modified-p field) t))))))
3338 ;;; Apropos protection overlays:
3340 ;; These exist for nasty users who will try to delete parts of the
3341 ;; snippet outside the active field. Actual protection happens in
3342 ;; `yas--on-protection-overlay-modification'.
3344 ;; Currently this signals an error which inhibits the command. For
3345 ;; commands that move point (like `kill-line'), point is restored in
3346 ;; the `yas--post-command-handler' using a global
3347 ;; `yas--protection-violation' variable.
3349 ;; Alternatively, I've experimented with an implementation that
3350 ;; commits the snippet before actually calling `this-command'
3351 ;; interactively, and then signals an error, which is ignored. but
3352 ;; blocks all other million modification hooks. This presented some
3353 ;; problems with stacked expansion.
3355 (defun yas--make-move-field-protection-overlays (snippet field)
3356 "Place protection overlays surrounding SNIPPET's FIELD.
3358 Move the overlays, or create them if they do not exit."
3359 (let ((start (yas--field-start field))
3360 (end (yas--field-end field)))
3361 ;; First check if the (1+ end) is contained in the buffer,
3362 ;; otherwise we'll have to do a bit of cheating and silently
3363 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3364 ;; when using stacked expansion
3366 (when (< (buffer-size) end)
3368 (yas--inhibit-overlay-hooks
3369 (goto-char (point-max))
3371 ;; go on to normal overlay creation/moving
3373 (cond ((and yas--field-protection-overlays
3374 (every #'overlay-buffer yas--field-protection-overlays))
3375 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3376 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3378 (setq yas--field-protection-overlays
3379 (list (make-overlay (1- start) start nil t nil)
3380 (make-overlay end (1+ end) nil t nil)))
3381 (dolist (ov yas--field-protection-overlays)
3382 (overlay-put ov 'face 'yas--field-debug-face)
3383 (overlay-put ov 'yas--snippet snippet)
3384 ;; (overlay-put ov 'evaporate t)
3385 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3387 (defvar yas--protection-violation nil
3388 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3390 Functions in the `post-command-hook', for example
3391 `yas--post-command-handler' can check it and reset its value to
3392 nil. The variables value is the point where the violation
3395 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3396 "Signals a snippet violation, then issues error.
3398 The error should be ignored in `debug-ignored-errors'"
3399 (unless yas--inhibit-overlay-hooks
3400 (cond ((not (or after?
3401 (yas--undo-in-progress)))
3402 (setq yas--protection-violation (point))
3403 (error "Exit the snippet first!")))))
3405 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3408 ;; Snippet expansion and "stacked" expansion:
3410 ;; Stacked expansion is when you try to expand a snippet when already
3411 ;; inside a snippet expansion.
3413 ;; The parent snippet does not run its fields modification hooks
3414 ;; (`yas--on-field-overlay-modification' and
3415 ;; `yas--on-protection-overlay-modification') while the child snippet
3416 ;; is active. This means, among other things, that the mirrors of the
3417 ;; parent snippet are not updated, this only happening when one exits
3418 ;; the child snippet.
3420 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3421 ;; bits of code in `yas-expand-snippet' and
3422 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3425 ;; This was thought to be safer in an undo/redo perspective, but
3426 ;; maybe the correct implementation is to make the globals
3427 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3428 ;; snippet-local and be active even while the child snippet is
3429 ;; running. This would mean a lot of overlay modification hooks
3430 ;; running, but if managed correctly (including overlay priorities)
3431 ;; they should account for all situations...
3433 (defun yas-expand-snippet (content &optional start end expand-env)
3434 "Expand snippet CONTENT at current point.
3436 Text between START and END will be deleted before inserting
3437 template. EXPAND-ENV is are let-style variable to value bindings
3438 considered when expanding the snippet."
3439 (run-hooks 'yas-before-expand-snippet-hook)
3442 (let* ((yas-selected-text (or yas-selected-text
3443 (and (region-active-p)
3444 (buffer-substring-no-properties (region-beginning)
3447 (and (region-active-p)
3451 (and (region-active-p)
3454 (to-delete (and start
3456 (buffer-substring-no-properties start end)))
3459 (setq yas--indent-original-column (current-column))
3460 ;; Delete the region to delete, this *does* get undo-recorded.
3462 (when (and to-delete
3464 (delete-region start end))
3466 (cond ((listp content)
3467 ;; x) This is a snippet-command
3469 (yas--eval-lisp-no-saves content))
3471 ;; x) This is a snippet-snippet :-)
3473 ;; Narrow the region down to the content, shoosh the
3474 ;; `buffer-undo-list', and create the snippet, the new
3475 ;; snippet updates its mirrors once, so we are left with
3476 ;; some plain text. The undo action for deleting this
3477 ;; plain text will get recorded at the end.
3479 ;; stacked expansion: also shoosh the overlay modification hooks
3481 (narrow-to-region start start)
3482 (let ((buffer-undo-list t))
3483 ;; snippet creation might evaluate users elisp, which
3484 ;; might generate errors, so we have to be ready to catch
3485 ;; them mostly to make the undo information
3487 (setq yas--start-column (save-restriction (widen) (current-column)))
3488 (yas--inhibit-overlay-hooks
3491 (eval `(let* ,expand-env
3493 (yas--snippet-create (point-min) (point-max))))
3495 (yas--snippet-create (point-min) (point-max)))))))
3497 ;; stacked-expansion: This checks for stacked expansion, save the
3498 ;; `yas--previous-active-field' and advance its boundary.
3500 (let ((existing-field (and yas--active-field-overlay
3501 (overlay-buffer yas--active-field-overlay)
3502 (overlay-get yas--active-field-overlay 'yas--field))))
3503 (when existing-field
3504 (setf (yas--snippet-previous-active-field snippet) existing-field)
3505 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3507 ;; Exit the snippet immediately if no fields
3509 (unless (yas--snippet-fields snippet)
3510 (yas-exit-snippet snippet))
3512 ;; Push two undo actions: the deletion of the inserted contents of
3513 ;; the new snippet (without the "key") followed by an apply of
3514 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3516 ;; A small exception, if `yas-also-auto-indent-first-line'
3517 ;; is t and `yas--indent' decides to indent the line to a
3518 ;; point before the actual expansion point, undo would be
3519 ;; messed up. We call the early point "newstart"". case,
3520 ;; and attempt to fix undo.
3522 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3523 (end (overlay-end (yas--snippet-control-overlay snippet))))
3524 (when (< newstart start)
3525 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3526 (push (cons newstart end) buffer-undo-list)
3527 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3529 ;; Now, schedule a move to the first field
3531 (let ((first-field (car (yas--snippet-fields snippet))))
3533 (sit-for 0) ;; fix issue 125
3534 (yas--move-to-field snippet first-field)))
3535 (yas--message 3 "snippet expanded.")
3538 (defun yas--take-care-of-redo (beg end snippet)
3539 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3541 Meant to exit in the `buffer-undo-list'."
3542 ;; slightly optimize: this action is only needed for snippets with
3543 ;; at least one field
3544 (when (yas--snippet-fields snippet)
3545 (yas--commit-snippet snippet)))
3547 (defun yas--snippet-revive (beg end snippet)
3548 "Revives SNIPPET and creates a control overlay from BEG to END.
3550 BEG and END are, we hope, the original snippets boundaries. All
3551 the markers/points exiting existing inside SNIPPET should point
3552 to their correct locations *at the time the snippet is revived*.
3554 After revival, push the `yas--take-care-of-redo' in the
3556 ;; Reconvert all the points to markers
3558 (yas--points-to-markers snippet)
3559 ;; When at least one editable field existed in the zombie snippet,
3560 ;; try to revive the whole thing...
3562 (let ((target-field (or (yas--snippet-active-field snippet)
3563 (car (yas--snippet-fields snippet)))))
3565 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3566 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3568 (yas--move-to-field snippet target-field)
3570 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3571 buffer-undo-list))))
3573 (defun yas--snippet-create (begin end)
3574 "Creates a snippet from an template inserted between BEGIN and END.
3576 Returns the newly created snippet."
3577 (let ((snippet (yas--make-snippet)))
3579 (yas--snippet-parse-create snippet)
3581 ;; Sort and link each field
3582 (yas--snippet-sort-fields snippet)
3584 ;; Create keymap overlay for snippet
3585 (setf (yas--snippet-control-overlay snippet)
3586 (yas--make-control-overlay snippet (point-min) (point-max)))
3589 (goto-char (point-max))
3594 ;;; Apropos adjacencies and "fom's":
3596 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3597 ;; recently expanded snippet, we might actually have many fields,
3598 ;; mirrors (and the snippet exit) in the very same position in the
3599 ;; buffer. Therefore we need to single-link the
3600 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3601 ;; according to their original positions in the buffer.
3603 ;; Then we have operation `yas--advance-end-maybe' and
3604 ;; `yas--advance-start-maybe', which conditionally push the starts and
3605 ;; ends of these foms down the chain.
3607 ;; This allows for like the printf with the magic ",":
3609 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3610 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3612 (defun yas--fom-start (fom)
3613 (cond ((yas--field-p fom)
3614 (yas--field-start fom))
3615 ((yas--mirror-p fom)
3616 (yas--mirror-start fom))
3618 (yas--exit-marker fom))))
3620 (defun yas--fom-end (fom)
3621 (cond ((yas--field-p fom)
3622 (yas--field-end fom))
3623 ((yas--mirror-p fom)
3624 (yas--mirror-end fom))
3626 (yas--exit-marker fom))))
3628 (defun yas--fom-next (fom)
3629 (cond ((yas--field-p fom)
3630 (yas--field-next fom))
3631 ((yas--mirror-p fom)
3632 (yas--mirror-next fom))
3634 (yas--exit-next fom))))
3636 (defun yas--fom-parent-field (fom)
3637 (cond ((yas--field-p fom)
3638 (yas--field-parent-field fom))
3639 ((yas--mirror-p fom)
3640 (yas--mirror-parent-field fom))
3644 (defun yas--calculate-adjacencies (snippet)
3645 "Calculate adjacencies for fields or mirrors of SNIPPET.
3647 This is according to their relative positions in the buffer, and
3648 has to be called before the $-constructs are deleted."
3649 (cl-flet ((yas--fom-set-next-fom (fom nextfom)
3650 (cond ((yas--field-p fom)
3651 (setf (yas--field-next fom) nextfom))
3652 ((yas--mirror-p fom)
3653 (setf (yas--mirror-next fom) nextfom))
3655 (setf (yas--exit-next fom) nextfom))))
3656 (yas--compare-fom-begs (fom1 fom2)
3657 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3658 (yas--mirror-p fom2)
3659 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3660 (yas--link-foms (fom1 fom2)
3661 (yas--fom-set-next-fom fom1 fom2)))
3662 ;; make some yas--field, yas--mirror and yas--exit soup
3664 (when (yas--snippet-exit snippet)
3665 (push (yas--snippet-exit snippet) soup))
3666 (dolist (field (yas--snippet-fields snippet))
3668 (dolist (mirror (yas--field-mirrors field))
3669 (push mirror soup)))
3672 #'yas--compare-fom-begs))
3674 (reduce #'yas--link-foms soup)))))
3676 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3677 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3679 Use the tightest containing field if more than one field contains
3680 the mirror. Intended to be called *before* the dollar-regions are
3682 (let ((min (point-min))
3684 (dolist (field (yas--snippet-fields snippet))
3685 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3686 (<= (yas--mirror-end mirror) (yas--field-end field))
3687 (< min (yas--field-start field))
3688 (< (yas--field-end field) max))
3689 (setq min (yas--field-start field)
3690 max (yas--field-end field))
3691 (setf (yas--mirror-parent-field mirror) field)))))
3693 (defun yas--advance-end-maybe (fom newend)
3694 "Maybe advance FOM's end to NEWEND if it needs it.
3698 * call `yas--advance-start-maybe' on FOM's next fom.
3700 * in case FOM is field call `yas--advance-end-maybe' on its parent
3703 Also, if FOM is an exit-marker, always call
3704 `yas--advance-start-maybe' on its next fom. This is because
3705 exit-marker have identical start and end markers."
3706 (cond ((and fom (< (yas--fom-end fom) newend))
3707 (set-marker (yas--fom-end fom) newend)
3708 (yas--advance-start-maybe (yas--fom-next fom) newend)
3709 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3711 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3713 (defun yas--advance-start-maybe (fom newstart)
3714 "Maybe advance FOM's start to NEWSTART if it needs it.
3716 If it does, also call `yas--advance-end-maybe' on FOM."
3717 (when (and fom (< (yas--fom-start fom) newstart))
3718 (set-marker (yas--fom-start fom) newstart)
3719 (yas--advance-end-maybe fom newstart)))
3721 (defun yas--advance-end-of-parents-maybe (field newend)
3722 "Like `yas--advance-end-maybe' but for parent fields.
3724 Only works for fields and doesn't care about the start of the
3725 next FOM. Works its way up recursively for parents of parents."
3727 (< (yas--field-end field) newend))
3728 (set-marker (yas--field-end field) newend)
3729 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3731 (defvar yas--dollar-regions nil
3732 "When expanding the snippet the \"parse-create\" functions add
3733 cons cells to this var.")
3735 (defvar yas--backquote-markers-and-strings nil
3736 "List of (MARKER . STRING) marking where the values from
3737 backquoted lisp expressions should be inserted at the end of
3740 (defun yas--snippet-parse-create (snippet)
3741 "Parse a recently inserted snippet template, creating all
3742 necessary fields, mirrors and exit points.
3744 Meant to be called in a narrowed buffer, does various passes"
3745 (let ((parse-start (point)))
3746 ;; Reset the yas--dollar-regions
3748 (setq yas--dollar-regions nil)
3749 ;; protect just the backquotes
3751 (yas--protect-escapes nil '(?`))
3752 ;; replace all backquoted expressions
3754 (goto-char parse-start)
3755 (yas--save-backquotes)
3756 ;; protect escaped characters
3758 (yas--protect-escapes)
3759 ;; parse fields with {}
3761 (goto-char parse-start)
3762 (yas--field-parse-create snippet)
3763 ;; parse simple mirrors and fields
3765 (goto-char parse-start)
3766 (yas--simple-mirror-parse-create snippet)
3767 ;; parse mirror transforms
3769 (goto-char parse-start)
3770 (yas--transform-mirror-parse-create snippet)
3771 ;; calculate adjacencies of fields and mirrors
3773 (yas--calculate-adjacencies snippet)
3774 ;; Delete $-constructs
3776 (yas--delete-regions yas--dollar-regions)
3777 ;; restore backquoted expression values
3779 (yas--restore-backquotes)
3782 (goto-char parse-start)
3783 (yas--restore-escapes)
3784 ;; update mirrors for the first time
3786 (yas--update-mirrors snippet)
3787 ;; indent the best we can
3789 (goto-char parse-start)
3790 (yas--indent snippet)))
3792 (defun yas--indent-according-to-mode (snippet-markers)
3793 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3794 ;;; Apropos indenting problems....
3796 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3797 ;; is available. Some implementations of these functions delete text
3798 ;; before they insert. If there happens to be a marker just after
3799 ;; the text being deleted, the insertion actually happens after the
3800 ;; marker, which misplaces it.
3802 ;; This would also happen if we had used overlays with the
3803 ;; `front-advance' property set to nil.
3805 ;; This is why I have these `trouble-markers', they are the ones at
3806 ;; they are the ones at the first non-whitespace char at the line
3807 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3808 ;; we should be at the correct to restore them to. All other
3809 ;; non-trouble-markers have been *pushed* and don't need special
3812 (goto-char (yas--real-line-beginning))
3813 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3819 (indent-according-to-mode)
3820 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3822 (mapc #'(lambda (marker)
3823 (set-marker marker (point)))
3826 (defvar yas--indent-original-column nil)
3827 (defun yas--indent (snippet)
3828 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3829 ;; Look for those $>
3831 (while (re-search-forward "$>" nil t)
3832 (delete-region (match-beginning 0) (match-end 0))
3833 (when (not (eq yas-indent-line 'auto))
3834 (yas--indent-according-to-mode snippet-markers))))
3835 ;; Now do stuff for 'fixed and 'auto
3837 (cond ((eq yas-indent-line 'fixed)
3838 (while (and (zerop (forward-line))
3839 (zerop (current-column)))
3840 (indent-to-column yas--indent-original-column)))
3841 ((eq yas-indent-line 'auto)
3842 (let ((end (set-marker (make-marker) (point-max)))
3843 (indent-first-line-p yas-also-auto-indent-first-line))
3844 (while (and (zerop (if indent-first-line-p
3847 (setq indent-first-line-p nil))
3851 (yas--indent-according-to-mode snippet-markers))))
3855 (defun yas--collect-snippet-markers (snippet)
3856 "Make a list of all the markers used by SNIPPET."
3858 (dolist (field (yas--snippet-fields snippet))
3859 (push (yas--field-start field) markers)
3860 (push (yas--field-end field) markers)
3861 (dolist (mirror (yas--field-mirrors field))
3862 (push (yas--mirror-start mirror) markers)
3863 (push (yas--mirror-end mirror) markers)))
3864 (let ((snippet-exit (yas--snippet-exit snippet)))
3865 (when (and snippet-exit
3866 (marker-buffer (yas--exit-marker snippet-exit)))
3867 (push (yas--exit-marker snippet-exit) markers)))
3870 (defun yas--real-line-beginning ()
3871 (let ((c (char-after (line-beginning-position)))
3872 (n (line-beginning-position)))
3873 (while (or (eql c ?\ )
3876 (setq c (char-after n)))
3879 (defun yas--escape-string (escaped)
3880 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3882 (defun yas--protect-escapes (&optional text escaped)
3883 "Protect all escaped characters with their numeric ASCII value.
3885 With optional string TEXT do it in string instead of buffer."
3886 (let ((changed-text text)
3887 (text-provided-p text))
3888 (mapc #'(lambda (escaped)
3890 (yas--replace-all (concat "\\" (char-to-string escaped))
3891 (yas--escape-string escaped)
3892 (when text-provided-p changed-text))))
3893 (or escaped yas--escaped-characters))
3896 (defun yas--restore-escapes (&optional text escaped)
3897 "Restore all escaped characters from their numeric ASCII value.
3899 With optional string TEXT do it in string instead of the buffer."
3900 (let ((changed-text text)
3901 (text-provided-p text))
3902 (mapc #'(lambda (escaped)
3904 (yas--replace-all (yas--escape-string escaped)
3905 (char-to-string escaped)
3906 (when text-provided-p changed-text))))
3907 (or escaped yas--escaped-characters))
3910 (defun yas--save-backquotes ()
3911 "Save all the \"`(lisp-expression)`\"-style expressions
3912 with their evaluated value into `yas--backquote-markers-and-strings'."
3913 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3914 (let ((current-string (match-string-no-properties 1)) transformed)
3915 (delete-region (match-beginning 0) (match-end 0))
3916 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3917 (goto-char (match-beginning 0))
3919 (let ((marker (make-marker)))
3920 (insert "Y") ;; quite horrendous, I love it :)
3921 (set-marker marker (point))
3923 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3925 (defun yas--restore-backquotes ()
3926 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3927 (while yas--backquote-markers-and-strings
3928 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3929 (marker (car marker-and-string))
3930 (string (cdr marker-and-string)))
3936 (set-marker marker nil)))))
3938 (defun yas--scan-sexps (from count)
3940 (with-syntax-table (standard-syntax-table)
3941 (scan-sexps from count))
3945 (defun yas--make-marker (pos)
3946 "Create a marker at POS with nil `marker-insertion-type'."
3947 (let ((marker (set-marker (make-marker) pos)))
3948 (set-marker-insertion-type marker nil)
3951 (defun yas--field-parse-create (snippet &optional parent-field)
3952 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3954 The following count as a field:
3956 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3958 * \"${n: text$(expression)}, the same with a lisp expression;
3959 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3961 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3963 When multiple expressions are found, only the last one counts."
3966 (while (re-search-forward yas--field-regexp nil t)
3967 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3968 (number (and (match-string-no-properties 1)
3969 (string-to-number (match-string-no-properties 1))))
3970 (brand-new-field (and real-match-end-0
3971 ;; break if on "$(" immediately
3972 ;; after the ":", this will be
3973 ;; caught as a mirror with
3975 (not (save-match-data
3976 (eq (string-match "$[ \t\n]*("
3977 (match-string-no-properties 2)) 0)))
3978 ;; allow ${0: some exit text}
3979 ;; (not (and number (zerop number)))
3980 (yas--make-field number
3981 (yas--make-marker (match-beginning 2))
3982 (yas--make-marker (1- real-match-end-0))
3984 (when brand-new-field
3985 (goto-char real-match-end-0)
3986 (push (cons (1- real-match-end-0) real-match-end-0)
3987 yas--dollar-regions)
3988 (push (cons (match-beginning 0) (match-beginning 2))
3989 yas--dollar-regions)
3990 (push brand-new-field (yas--snippet-fields snippet))
3993 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
3994 (goto-char (point-min))
3995 (yas--field-parse-create snippet brand-new-field)))))))
3996 ;; if we entered from a parent field, now search for the
3997 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
3998 ;; primary field transformations
4002 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4003 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4004 ;; commit the primary field transformation if:
4006 ;; 1. we don't find it in yas--dollar-regions (a subnested
4007 ;; field) might have already caught it.
4009 ;; 2. we really make sure we have either two '$' or some
4010 ;; text and a '$' after the colon ':'. This is a FIXME: work
4011 ;; my regular expressions and end these ugly hacks.
4013 (when (and real-match-end-1
4014 (not (member (cons (match-beginning 0)
4016 yas--dollar-regions))
4018 (char-before (1- (match-beginning 1))))))
4019 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4021 (setf (yas--field-transform parent-field)
4022 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4023 (push (cons (match-beginning 0) real-match-end-1)
4024 yas--dollar-regions)))))))
4026 (defun yas--transform-mirror-parse-create (snippet)
4027 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4028 (while (re-search-forward yas--transform-mirror-regexp nil t)
4029 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4030 (number (string-to-number (match-string-no-properties 1)))
4032 (not (zerop number))
4033 (yas--snippet-find-field snippet number)))
4035 (and real-match-end-0
4037 (yas--make-mirror (yas--make-marker (match-beginning 0))
4038 (yas--make-marker (match-beginning 0))
4040 (yas--restore-escapes
4041 (buffer-substring-no-properties (match-beginning 2)
4042 (1- real-match-end-0))))))))
4043 (when brand-new-mirror
4044 (push brand-new-mirror
4045 (yas--field-mirrors field))
4046 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4047 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4049 (defun yas--simple-mirror-parse-create (snippet)
4050 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4051 (while (re-search-forward yas--simple-mirror-regexp nil t)
4052 (let ((number (string-to-number (match-string-no-properties 1))))
4053 (cond ((zerop number)
4055 (setf (yas--snippet-exit snippet)
4056 (yas--make-exit (yas--make-marker (match-end 0))))
4058 (goto-char (match-beginning 0))
4059 (when yas-wrap-around-region
4060 (cond (yas-selected-text
4061 (insert yas-selected-text))
4062 ((and (eq yas-wrap-around-region 'cua)
4065 (insert (prog1 (get-register ?0)
4066 (set-register ?0 nil))))))
4067 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4068 yas--dollar-regions)))
4070 (let ((field (yas--snippet-find-field snippet number)))
4072 (let ((brand-new-mirror (yas--make-mirror
4073 (yas--make-marker (match-beginning 0))
4074 (yas--make-marker (match-beginning 0))
4076 (push brand-new-mirror
4077 (yas--field-mirrors field))
4078 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4079 (push (yas--make-field number
4080 (yas--make-marker (match-beginning 0))
4081 (yas--make-marker (match-beginning 0))
4083 (yas--snippet-fields snippet))))
4084 (push (cons (match-beginning 0) (match-end 0))
4085 yas--dollar-regions))))))
4087 (defun yas--delete-regions (regions)
4088 "Sort disjuct REGIONS by start point, then delete from the back."
4089 (mapc #'(lambda (reg)
4090 (delete-region (car reg) (cdr reg)))
4093 (>= (car r1) (car r2))))))
4095 (defun yas--update-mirrors (snippet)
4096 "Updates all the mirrors of SNIPPET."
4098 (dolist (field-and-mirror (sort
4099 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4100 ;; where F is the field that M is mirroring
4102 (mapcan #'(lambda (field)
4103 (mapcar #'(lambda (mirror)
4104 (cons field mirror))
4105 (yas--field-mirrors field)))
4106 (yas--snippet-fields snippet))
4107 ;; then sort this list so that entries with mirrors with parent
4108 ;; fields appear before. This was important for fixing #290, and
4109 ;; luckily also handles the case where a mirror in a field causes
4110 ;; another mirror to need reupdating
4112 #'(lambda (field-and-mirror1 field-and-mirror2)
4113 (yas--mirror-parent-field (cdr field-and-mirror1)))))
4114 (let* ((field (car field-and-mirror))
4115 (mirror (cdr field-and-mirror))
4116 (parent-field (yas--mirror-parent-field mirror)))
4117 ;; before updating a mirror with a parent-field, maybe advance
4121 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4122 ;; update this mirror
4124 (yas--mirror-update-display mirror field)
4125 ;; `yas--place-overlays' is needed if the active field and
4126 ;; protected overlays have been changed because of insertions
4127 ;; in `yas--mirror-update-display'
4129 (when (eq field (yas--snippet-active-field snippet))
4130 (yas--place-overlays snippet field))))))
4132 (defun yas--mirror-update-display (mirror field)
4133 "Update MIRROR according to FIELD (and mirror transform)."
4135 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4136 (reflection (and (not (and mirror-parent-field
4137 (yas--field-modified-p mirror-parent-field)))
4138 (or (yas--apply-transform mirror field 'empty-on-nil)
4139 (yas--field-text-for-display field)))))
4140 (when (and reflection
4141 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4142 (yas--mirror-end mirror)))))
4143 (goto-char (yas--mirror-start mirror))
4144 (yas--inhibit-overlay-hooks
4145 (insert reflection))
4146 (if (> (yas--mirror-end mirror) (point))
4147 (delete-region (point) (yas--mirror-end mirror))
4148 (set-marker (yas--mirror-end mirror) (point))
4149 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4150 ;; super-special advance
4151 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4153 (defun yas--field-update-display (field snippet)
4154 "Much like `yas--mirror-update-display', but for fields."
4155 (when (yas--field-transform field)
4156 (let ((transformed (and (not (eq (yas--field-number field) 0))
4157 (yas--apply-transform field field)))
4159 (when (and transformed
4160 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4161 (yas--field-end field)))))
4162 (setf (yas--field-modified-p field) t)
4163 (goto-char (yas--field-start field))
4164 (yas--inhibit-overlay-hooks
4165 (insert transformed)
4166 (if (> (yas--field-end field) (point))
4167 (delete-region (point) (yas--field-end field))
4168 (set-marker (yas--field-end field) (point))
4169 (yas--advance-start-maybe (yas--field-next field) (point)))
4173 ;;; Post-command hook:
4175 (defun yas--post-command-handler ()
4176 "Handles various yasnippet conditions after each command."
4177 (cond (yas--protection-violation
4178 (goto-char yas--protection-violation)
4179 (setq yas--protection-violation nil))
4180 ((eq 'undo this-command)
4182 ;; After undo revival the correct field is sometimes not
4183 ;; restored correctly, this condition handles that
4185 (let* ((snippet (car (yas--snippets-at-point)))
4186 (target-field (and snippet
4187 (find-if-not #'(lambda (field)
4188 (yas--field-probably-deleted-p snippet field))
4190 (cons (yas--snippet-active-field snippet)
4191 (yas--snippet-fields snippet)))))))
4193 (yas--move-to-field snippet target-field))))
4194 ((not (yas--undo-in-progress))
4195 ;; When not in an undo, check if we must commit the snippet
4196 ;; (user exited it).
4197 (yas--check-commit-snippet))))
4201 ;; The docstrings for some functions are generated dynamically
4202 ;; depending on the context.
4204 (put 'yas-expand 'function-documentation
4205 '(yas--expand-from-trigger-key-doc))
4206 (defun yas--expand-from-trigger-key-doc ()
4207 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4208 (let ((fallback-description
4209 (cond ((eq yas-fallback-behavior 'call-other-command)
4210 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4212 (format " call command `%s'." (pp-to-string fallback)))
4213 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4214 ((eq yas-fallback-behavior 'return-nil)
4217 ", defer to `yas-fallback-behaviour' (which see)"))))
4218 (concat "Expand a snippet before point. If no snippet
4219 expansion is possible,"
4220 fallback-description
4221 "\n\nOptional argument FIELD is for non-interactive use and is an
4222 object satisfying `yas--field-p' to restrict the expansion to.")))
4224 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4225 (defun yas--expand-from-keymap-doc ()
4226 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4227 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4228 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4229 (when (eq this-command 'describe-key)
4230 (let* ((vec (this-single-command-keys))
4231 (templates (mapcan #'(lambda (table)
4232 (yas--fetch table vec))
4233 (yas--get-snippet-tables)))
4234 (yas--direct-keymaps nil)
4235 (fallback (key-binding vec)))
4236 (concat "In this case, "
4238 (concat "these snippets are bound to this key:\n"
4239 (yas--template-pretty-list templates)
4240 "\n\nIf none of these expands, "))
4242 (format "fallback `%s' will be called." (pp-to-string fallback)))
4243 "no fallback keybinding is called."))))))
4245 (defun yas--template-pretty-list (templates)
4247 (yas-buffer-local-condition 'always))
4248 (dolist (plate templates)
4249 (setq acc (concat acc "\n*) "
4250 (propertize (concat "\\\\snippet `" (car plate) "'")
4251 'yasnippet (cdr plate)))))
4254 (define-button-type 'help-snippet-def
4255 :supertype 'help-xref
4256 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4257 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4259 (defun yas--snippet-description-finish-runonce ()
4260 "Final adjustments for the help buffer when snippets are concerned."
4261 (yas--create-snippet-xrefs)
4262 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4264 (defun yas--create-snippet-xrefs ()
4266 (goto-char (point-min))
4267 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4268 (let ((template (get-text-property (match-beginning 1)
4271 (help-xref-button 1 'help-snippet-def template)
4272 (kill-region (match-end 1) (match-end 0))
4273 (kill-region (match-beginning 0) (match-beginning 1)))))))
4275 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4276 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4278 Remaining args as in `yas-expand-snippet'."
4279 (let* ((table (gethash mode-symbol yas--tables))
4280 (yas--current-template (and table
4281 (gethash uuid (yas--table-uuidhash table)))))
4282 (when yas--current-template
4283 (yas-expand-snippet (yas--template-content yas--current-template)))))
4287 (defvar yas-verbosity 4
4288 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4290 (defun yas--message (level message &rest args)
4291 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4292 (when (> yas-verbosity level)
4293 (message (apply #'yas--format message args))))
4295 (defun yas--format (format-control &rest format-args)
4296 (apply #'format (concat "[yas] " format-control) format-args))
4303 ;; `locate-dominating-file'
4304 ;; `region-active-p'
4306 ;; added for compatibility in emacsen < 23
4307 (unless (>= emacs-major-version 23)
4308 (unless (fboundp 'region-active-p)
4309 (defun region-active-p () (and transient-mark-mode mark-active)))
4311 (unless (fboundp 'locate-dominating-file)
4312 (defvar locate-dominating-stop-dir-regexp
4313 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4314 "Regexp of directory names which stop the search in `locate-dominating-file'.
4315 Any directory whose name matches this regexp will be treated like
4316 a kind of root directory by `locate-dominating-file' which will stop its search
4317 when it bumps into it.
4318 The default regexp prevents fruitless and time-consuming attempts to find
4319 special files in directories in which filenames are interpreted as hostnames,
4320 or mount points potentially requiring authentication as a different user.")
4322 (defun locate-dominating-file (file name)
4323 "Look up the directory hierarchy from FILE for a file named NAME.
4324 Stop at the first parent directory containing a file NAME,
4325 and return the directory. Return nil if not found."
4326 ;; We used to use the above locate-dominating-files code, but the
4327 ;; directory-files call is very costly, so we're much better off doing
4328 ;; multiple calls using the code in here.
4330 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4331 ;; `name' in /home or in /.
4332 (setq file (abbreviate-file-name file))
4335 ;; `user' is not initialized outside the loop because
4336 ;; `file' may not exist, so we may have to walk up part of the
4337 ;; hierarchy before we find the "initial UUID".
4340 (while (not (or root
4342 ;; FIXME: Disabled this heuristic because it is sometimes
4344 ;; As a heuristic, we stop looking up the hierarchy of
4345 ;; directories as soon as we find a directory belonging
4346 ;; to another user. This should save us from looking in
4347 ;; things like /net and /afs. This assumes that all the
4348 ;; files inside a project belong to the same user.
4349 ;; (let ((prev-user user))
4350 ;; (setq user (nth 2 (file-attributes file)))
4351 ;; (and prev-user (not (equal user prev-user))))
4352 (string-match locate-dominating-stop-dir-regexp file)))
4353 (setq try (file-exists-p (expand-file-name name file)))
4354 (cond (try (setq root file))
4355 ((equal file (setq prev-file file
4356 file (file-name-directory
4357 (directory-file-name file))))
4361 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4362 ;; (when it execute forward-char) and interrupt the after change
4363 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4364 ;; invoked. Here's a way to reproduce it:
4366 ;; # open a *new* Emacs.
4367 ;; # load yasnippet.
4368 ;; # open a *new* .cpp file.
4369 ;; # input "inc" and press TAB to expand the snippet.
4370 ;; # select the `#include <...>` snippet.
4371 ;; # type inside `<>`
4373 (defadvice c-neutralize-syntax-in-CPP
4374 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4375 "Adviced `c-neutralize-syntax-in-CPP' to properly
4376 handle the end-of-buffer error fired in it by calling
4377 `forward-char' at the end of buffer."
4380 (error (message (error-message-string err)))))
4382 ;; disable c-electric-* serial command in YAS fields
4383 (add-hook 'c-mode-common-hook
4385 (dolist (k '(":" ">" ";" "<" "{" "}"))
4386 (define-key (symbol-value (make-local-variable 'yas-keymap))
4387 k 'self-insert-command))))
4389 ;;; Backward compatibility to yasnippet <= 0.7
4390 (defvar yas--exported-syms '(;; `defcustom's
4393 yas-prompt-functions
4395 yas-also-auto-indent-first-line
4397 yas-triggers-in-field
4398 yas-fallback-behavior
4399 yas-choose-keys-first
4400 yas-choose-tables-first
4403 yas-wrap-around-region
4406 yas-expand-only-for-last-commands
4407 yas-field-highlight-face
4409 ;; these vars can be customized as well
4415 yas-after-exit-snippet-hook
4416 yas-before-expand-snippet-hook
4417 yas-buffer-local-condition
4420 ;; prompting functions
4425 yas-completing-prompt
4428 ;; interactive functions
4433 yas-direct-keymaps-reload
4437 yas-compile-directory
4440 yas-expand-from-trigger-key
4441 yas-expand-from-keymap
4443 yas-visit-snippet-file
4445 yas-load-snippet-buffer
4448 yas-next-field-or-maybe-expand
4453 yas-exit-all-snippets
4454 yas-skip-and-clear-or-delete-char
4456 ;; symbols that I "exported" for use
4457 ;; in snippets and hookage
4475 yas-default-from-field
4478 yas-define-condition-cache
4479 yas-hippie-try-expand
4482 ;; debug definitions
4483 ;; yas-debug-snippet-vars
4484 ;; yas-exterminate-package
4487 ;; testing definitions
4488 ;; yas-should-expand
4489 ;; yas-should-not-expand
4491 ;; yas-make-file-or-dirs
4493 ;; yas-saving-variables
4494 ;; yas-call-with-snippet-dirs
4495 ;; yas-with-snippet-dirs
4497 "Exported yasnippet symbols.
4499 i.e. ones that I will try to keep in future yasnippet versions
4500 and ones that other elisp libraries can more or less safely rely
4503 (defvar yas--dont-backport '(yas-active-keys)
4504 "Exported symbols that don't map back to \"yas/*\" variants.")
4506 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4507 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4509 (make-obsolete-variable backported sym "yasnippet 0.8")
4510 (defvaralias backported sym))
4512 (make-obsolete backported sym "yasnippet 0.8")
4513 (defalias backported sym))))
4516 (provide 'yasnippet)
4518 ;;; yasnippet.el ends here
4521 ;; byte-compile-warnings: (not cl-functions)