1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.8.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas-global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas-reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas-snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas-minor-mode',
66 ;; this is bound to `yas-trigger-key' which you can customize.
68 ;; M-x yas-load-directory
70 ;; Prompts you for a directory hierarchy of snippets to load.
72 ;; M-x yas-insert-snippet
74 ;; Prompts you for possible snippet expansion if that is
75 ;; possible according to buffer-local and snippet-local
76 ;; expansion conditions. With prefix argument, ignore these
79 ;; M-x yas-visit-snippet-file
81 ;; Prompts you for possible snippet expansions like
82 ;; `yas-insert-snippet', but instead of expanding it, takes
83 ;; you directly to the snippet definition's file, if it
86 ;; M-x yas-new-snippet
88 ;; Lets you create a new snippet file in the correct
89 ;; subdirectory of `yas-snippet-dirs', according to the
92 ;; M-x yas-load-snippet-buffer
94 ;; When editing a snippet, this loads the snippet. This is
95 ;; bound to "C-c C-c" while in the `snippet-mode' editing
98 ;; M-x yas-tryout-snippet
100 ;; When editing a snippet, this opens a new empty buffer,
101 ;; sets it to the appropriate major mode and inserts the
102 ;; snippet there, so you can see what it looks like. This is
103 ;; bound to "C-c C-t" while in `snippet-mode'.
105 ;; M-x yas-describe-tables
107 ;; Lists known snippets in a separate buffer. User is
108 ;; prompted as to whether only the currently active tables
109 ;; are to be displayed, or all the tables for all major
112 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
113 ;; can optionally use it the preferred "prompting method", puting in
114 ;; your .emacs file, for example:
116 ;; (require 'dropdown-list)
117 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
119 ;; yas-completing-prompt))
121 ;; Also check out the customization group
123 ;; M-x customize-group RET yasnippet RET
125 ;; If you use the customization group to set variables
126 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
127 ;; "yasnippet.el" is present in the `load-path' *before* the
128 ;; `custom-set-variables' is executed in your .emacs file.
130 ;; For more information and detailed usage, refer to the project page:
131 ;; http://github.com/capitaomorte/yasnippet
140 ;;; User customizable variables
142 (defgroup yasnippet nil
143 "Yet Another Snippet extension"
146 (defvar yas--load-file-name load-file-name
147 "Store the filename that yasnippet.el was originally loaded from.")
149 (defcustom yas-snippet-dirs (remove nil
150 (list "~/.emacs.d/snippets"
151 (when yas--load-file-name
152 (concat (file-name-directory yas--load-file-name) "snippets"))))
153 "Directory or list of snippet dirs for each major mode.
155 The directory where user-created snippets are to be stored. Can
156 also be a list of directories. In that case, when used for
157 bulk (re)loading of snippets (at startup or via
158 `yas-reload-all'), directories appearing earlier in the list
159 shadow other dir's snippets. Also, the first directory is taken
160 as the default for storing the user's new snippets."
161 :type '(choice (string :tag "Single directory (string)")
162 (repeat :args (string) :tag "List of directories (strings)"))
165 :set #'(lambda (symbol new)
166 (let ((old (and (boundp symbol)
167 (symbol-value symbol))))
168 (set-default symbol new)
169 (unless (or (not (fboundp 'yas-reload-all))
173 (defun yas-snippet-dirs ()
174 "Returns `yas-snippet-dirs' (which see) as a list."
175 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
177 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
179 (defcustom yas-prompt-functions '(yas-x-prompt
181 yas-completing-prompt
184 "Functions to prompt for keys, templates, etc interactively.
186 These functions are called with the following arguments:
188 - PROMPT: A string to prompt the user
190 - CHOICES: a list of strings or objects.
192 - optional DISPLAY-FN : A function that, when applied to each of
193 the objects in CHOICES will return a string.
195 The return value of any function you put here should be one of
196 the objects in CHOICES, properly formatted with DISPLAY-FN (if
199 - To signal that your particular style of prompting is
200 unavailable at the moment, you can also have the function return
203 - To signal that the user quit the prompting process, you can
206 (signal 'quit \"user quit!\")."
207 :type '(repeat function)
210 (defcustom yas-indent-line 'auto
211 "Controls indenting applied to a recent snippet expansion.
213 The following values are possible:
215 - `fixed' Indent the snippet to the current column;
217 - `auto' Indent each line of the snippet with `indent-according-to-mode'
219 Every other value means don't apply any snippet-side indendation
220 after expansion (the manual per-line \"$>\" indentation still
222 :type '(choice (const :tag "Nothing" nothing)
223 (const :tag "Fixed" fixed)
224 (const :tag "Auto" auto))
227 (defcustom yas-also-auto-indent-first-line nil
228 "Non-nil means also auto indent first line according to mode.
230 Naturally this is only valid when `yas-indent-line' is `auto'"
234 (defcustom yas-snippet-revival t
235 "Non-nil means re-activate snippet fields after undo/redo."
239 (defcustom yas-trigger-key "TAB"
240 "The key bound to `yas-expand' when function `yas-minor-mode' is active.
242 Value is a string that is converted to the internal Emacs key
243 representation using `read-kbd-macro'."
246 :set #'(lambda (symbol key)
247 (let ((old (and (boundp symbol)
248 (symbol-value symbol))))
249 (set-default symbol key)
250 ;; On very first loading of this defcustom,
251 ;; `yas-trigger-key' is *not* loaded.
252 (if (fboundp 'yas--trigger-key-reload)
253 (yas--trigger-key-reload old)))))
255 (defcustom yas-next-field-key '("TAB" "<tab>")
256 "The key to navigate to next field when a snippet is active.
258 Value is a string that is converted to the internal Emacs key
259 representation using `read-kbd-macro'.
261 Can also be a list of strings."
262 :type '(choice (string :tag "String")
263 (repeat :args (string) :tag "List of strings"))
265 :set #'(lambda (symbol val)
266 (set-default symbol val)
267 (if (fboundp 'yas--init-yas-in-snippet-keymap)
268 (yas--init-yas-in-snippet-keymap))))
271 (defcustom yas-prev-field-key '("<backtab>" "<S-tab>")
272 "The key to navigate to previous field when a snippet is active.
274 Value is a string that is converted to the internal Emacs key
275 representation using `read-kbd-macro'.
277 Can also be a list of strings."
278 :type '(choice (string :tag "String")
279 (repeat :args (string) :tag "List of strings"))
281 :set #'(lambda (symbol val)
282 (set-default symbol val)
283 (if (fboundp 'yas--init-yas-in-snippet-keymap)
284 (yas--init-yas-in-snippet-keymap))))
286 (defcustom yas-skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
287 "The key to clear the currently active field.
289 Value is a string that is converted to the internal Emacs key
290 representation using `read-kbd-macro'.
292 Can also be a list of strings."
293 :type '(choice (string :tag "String")
294 (repeat :args (string) :tag "List of strings"))
296 :set #'(lambda (symbol val)
297 (set-default symbol val)
298 (if (fboundp 'yas--init-yas-in-snippet-keymap)
299 (yas--init-yas-in-snippet-keymap))))
301 (defcustom yas-triggers-in-field nil
302 "If non-nil, `yas-next-field-key' can trigger stacked expansions.
304 Otherwise, `yas-next-field-key' just tries to move on to the next
309 (defcustom yas-fallback-behavior 'call-other-command
310 "How to act when `yas-trigger-key' does *not* expand a snippet.
312 - `call-other-command' means try to temporarily disable YASnippet
313 and call the next command bound to `yas-trigger-key'.
315 - nil or the symbol `return-nil' mean do nothing. (and
316 `yas-expand' returns nil)
318 - A lisp form (apply COMMAND . ARGS) means interactively call
319 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
320 with ARGS as arguments."
321 :type '(choice (const :tag "Call previous command" call-other-command)
322 (const :tag "Do nothing" return-nil))
325 (defcustom yas-choose-keys-first nil
326 "If non-nil, prompt for snippet key first, then for template.
328 Otherwise prompts for all possible snippet names.
330 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
334 (defcustom yas-choose-tables-first nil
335 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
337 Otherwise, user chooses between the merging together of all
340 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
344 (defcustom yas-use-menu 'abbreviate
345 "Display a YASnippet menu in the menu bar.
347 When non-nil, submenus for each snippet table will be listed
348 under the menu \"Yasnippet\".
350 - If set to `abbreviate', only the current major-mode
351 menu and the modes set in `yas-extra-modes' are listed.
353 - If set to `full', every submenu is listed
355 - It set to nil, don't display a menu at all (this requires a
356 `yas-reload-all' call if the menu is already visible).
358 Any other non-nil value, every submenu is listed."
359 :type '(choice (const :tag "Full" full)
360 (const :tag "Abbreviate" abbreviate)
361 (const :tag "No menu" nil))
364 (defcustom yas-trigger-symbol (if (eq window-system 'mac)
365 (char-to-string ?\x21E5) ;; little ->| sign
367 "The text that will be used in menu to represent the trigger."
371 (defcustom yas-wrap-around-region nil
372 "If non-nil, snippet expansion wraps around selected region.
374 The wrapping occurs just before the snippet's exit marker. This
375 can be overriden on a per-snippet basis."
379 (defcustom yas-good-grace t
380 "If non-nil, don't raise errors in inline elisp evaluation.
382 An error string \"[yas] error\" is returned instead."
386 (defcustom yas-visit-from-menu nil
387 "If non-nil visit snippets's files from menu, instead of expanding them.
389 This cafn only work when snippets are loaded from files."
393 (defcustom yas-expand-only-for-last-commands nil
394 "List of `last-command' values to restrict tab-triggering to, or nil.
396 Leave this set at nil (the default) to be able to trigger an
397 expansion simply by placing the cursor after a valid tab trigger,
398 using whichever commands.
400 Optionallly, set this to something like '(self-insert-command) if
401 you to wish restrict expansion to only happen when the last
402 letter of the snippet tab trigger was typed immediately before
403 the trigger key itself."
404 :type '(repeat function)
407 ;; Only two faces, and one of them shouldn't even be used...
409 (defface yas-field-highlight-face
410 '((t (:inherit 'region)))
411 "The face used to highlight the currently active field of a snippet"
414 (defface yas--field-debug-face
416 "The face used for debugging some overlays normally hidden"
420 ;;; User can also customize the next defvars
422 (defun yas--define-some-keys (keys keymap definition)
423 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
424 (let ((keys (or (and (listp keys) keys)
427 (define-key keymap (read-kbd-macro key) definition))))
429 (defun yas--init-yas-in-snippet-keymap ()
431 (let ((map (make-sparse-keymap)))
432 (mapc #'(lambda (binding)
433 (yas--define-some-keys (car binding) map (cdr binding)))
434 `((,yas-next-field-key . yas-next-field-or-maybe-expand)
435 (,yas-prev-field-key . yas-prev-field)
436 ("C-g" . yas-abort-snippet)
437 (,yas-skip-and-clear-key . yas-skip-and-clear-or-delete-char)))
440 (defvar yas-keymap (yas--init-yas-in-snippet-keymap)
441 "The keymap active while a snippet expansion is in progress.")
443 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
444 "List of character syntaxes used to find a trigger key before point.
445 The list is tried in the order while scanning characters
446 backwards from point. For example, if the list is '(\"w\" \"w_\")
447 first look for trigger keys which are composed exclusively of
448 \"word\"-syntax characters, and then, if that fails, look for
449 keys which are either of \"word\" or \"symbol\"
450 syntax. Triggering after
454 will, according to the \"w\" element first try \"bar\". If that
455 isn't a trigger key, \"foo-bar\" is tried, respecting a second
458 (defvar yas-after-exit-snippet-hook
460 "Hooks to run after a snippet exited.
462 The hooks will be run in an environment where some variables bound to
465 `yas-snippet-beg' : The beginning of the region of the snippet.
467 `yas-snippet-end' : Similar to beg.
469 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
471 (defvar yas-before-expand-snippet-hook
473 "Hooks to run just before expanding a snippet.")
475 (defvar yas-buffer-local-condition
476 '(if (and (or (fourth (syntax-ppss))
477 (fifth (syntax-ppss)))
478 (eq (symbol-function this-command) 'yas-expand-from-trigger-key))
479 '(require-snippet-condition . force-in-comment)
481 "Snippet expanding condition.
483 This variable is a lisp form which is evaluated everytime a
484 snippet expansion is attemped:
486 * If it evaluates to nil, no snippets can be expanded.
488 * If it evaluates to the a cons (require-snippet-condition
491 * Snippets bearing no \"# condition:\" directive are not
494 * Snippets bearing conditions that evaluate to nil (or
495 produce an error) won't be onsidered.
497 * If the snippet has a condition that evaluates to non-nil
500 * If REQUIREMENT is t, the snippet is considered
502 * If REQUIREMENT is `eq' RESULT, the snippet is
505 * Otherwise, the snippet is not considered.
507 * If it evaluates to the symbol 'always, all snippets are
508 considered for expansion, regardless of any conditions.
510 * If it evaluates to t or some other non-nil value
512 * Snippet bearing no conditions, or conditions that
513 evaluate to non-nil, are considered for expansion.
515 * Otherwise, the snippet is not considered.
517 Here's an example preventing snippets from being expanded from
518 inside comments, in `python-mode' only, with the exception of
519 snippets returning the symbol 'force-in-comment in their
522 (add-hook 'python-mode-hook
524 (setq yas-buffer-local-condition
525 '(if (python-in-string/comment)
526 '(require-snippet-condition . force-in-comment)
529 The default value is similar, it filters out potential snippet
530 expansions inside comments and string literals, unless the
531 snippet itself contains a condition that returns the symbol
532 `force-in-comment'.")
535 ;;; Internal variables
537 (defvar yas--version "0.8.0 (beta)")
539 (defvar yas--menu-table (make-hash-table)
540 "A hash table of MAJOR-MODE symbols to menu keymaps.")
542 (defvar yas--known-modes
543 '(ruby-mode rst-mode markdown-mode)
544 "A list of mode which is well known but not part of emacs.")
546 (defvar yas--escaped-characters
547 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
548 "List of characters which *might* need to be escaped.")
550 (defconst yas--field-regexp
551 "${\\([0-9]+:\\)?\\([^}]*\\)}"
552 "A regexp to *almost* recognize a field.")
554 (defconst yas--multi-dollar-lisp-expression-regexp
555 "$+[ \t\n]*\\(([^)]*)\\)"
556 "A regexp to *almost* recognize a \"$(...)\" expression.")
558 (defconst yas--backquote-lisp-expression-regexp
560 "A regexp to recognize a \"`lisp-expression`\" expression." )
562 (defconst yas--transform-mirror-regexp
563 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
564 "A regexp to *almost* recognize a mirror with a transform.")
566 (defconst yas--simple-mirror-regexp
568 "A regexp to recognize a simple mirror.")
570 (defvar yas--snippet-id-seed 0
571 "Contains the next id for a snippet.")
573 (defun yas--snippet-next-id ()
574 (let ((id yas--snippet-id-seed))
575 (incf yas--snippet-id-seed)
581 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
582 (defvar last-buffer-undo-list nil)
584 (defvar yas--minor-mode-menu nil
585 "Holds the YASnippet menu")
587 (defun yas--init-minor-keymap ()
588 (let ((map (make-sparse-keymap)))
590 (easy-menu-define yas--minor-mode-menu
592 "Menu used when `yas-minor-mode' is active."
595 ["Expand trigger" yas-expand
596 :help "Possibly expand tab trigger before point"]
597 ["Insert at point..." yas-insert-snippet
598 :help "Prompt for an expandable snippet and expand it at point"]
599 ["New snippet..." yas-new-snippet
600 :help "Create a new snippet in an appropriate directory"]
601 ["Visit snippet file..." yas-visit-snippet-file
602 :help "Prompt for an expandable snippet and find its file"]
604 ("Snippet menu behaviour"
605 ["Visit snippets" (setq yas-visit-from-menu t)
606 :help "Visit snippets from the menu"
607 :active t :style radio :selected yas-visit-from-menu]
608 ["Expand snippets" (setq yas-visit-from-menu nil)
609 :help "Expand snippets from the menu"
610 :active t :style radio :selected (not yas-visit-from-menu)]
612 ["Show all known modes" (setq yas-use-menu 'full)
613 :help "Show one snippet submenu for each loaded table"
614 :active t :style radio :selected (eq yas-use-menu 'full)]
615 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
616 :help "Show only snippet submenus for the current active modes"
617 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
619 ["Auto" (setq yas-indent-line 'auto)
620 :help "Indent each line of the snippet with `indent-according-to-mode'"
621 :active t :style radio :selected (eq yas-indent-line 'auto)]
622 ["Fixed" (setq yas-indent-line 'fixed)
623 :help "Indent the snippet to the current column"
624 :active t :style radio :selected (eq yas-indent-line 'fixed)]
625 ["None" (setq yas-indent-line 'none)
626 :help "Don't apply any particular snippet indentation after expansion"
627 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
629 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
630 (not yas-also-auto-indent-first-line))
631 :help "When auto-indenting also, auto indent the first line menu"
632 :active (eq yas-indent-line 'auto)
633 :style toggle :selected yas-also-auto-indent-first-line]
636 ["System X-widget" (setq yas-prompt-functions
638 (remove 'yas-x-prompt
639 yas-prompt-functions)))
640 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
641 :active t :style radio :selected (eq (car yas-prompt-functions)
643 ["Dropdown-list" (setq yas-prompt-functions
644 (cons 'yas-dropdown-prompt
645 (remove 'yas-dropdown-prompt
646 yas-prompt-functions)))
647 :help "Use a special dropdown list"
648 :active t :style radio :selected (eq (car yas-prompt-functions)
649 'yas-dropdown-prompt)]
650 ["Ido" (setq yas-prompt-functions
651 (cons 'yas-ido-prompt
652 (remove 'yas-ido-prompt
653 yas-prompt-functions)))
654 :help "Use an ido-style minibuffer prompt"
655 :active t :style radio :selected (eq (car yas-prompt-functions)
657 ["Completing read" (setq yas-prompt-functions
658 (cons 'yas-completing-prompt
659 (remove 'yas-completing-prompt
660 yas-prompt-functions)))
661 :help "Use a normal minibuffer prompt"
662 :active t :style radio :selected (eq (car yas-prompt-functions)
663 'yas-completing-prompt)]
666 ["Wrap region in exit marker"
667 (setq yas-wrap-around-region
668 (not yas-wrap-around-region))
669 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
670 :style toggle :selected yas-wrap-around-region]
671 ["Allow stacked expansions "
672 (setq yas-triggers-in-field
673 (not yas-triggers-in-field))
674 :help "If non-nil allow snippets to be triggered inside other snippet fields"
675 :style toggle :selected yas-triggers-in-field]
676 ["Revive snippets on undo "
677 (setq yas-snippet-revival
678 (not yas-snippet-revival))
679 :help "If non-nil allow snippets to become active again after undo"
680 :style toggle :selected yas-snippet-revival]
683 (not yas-good-grace))
684 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
685 :style toggle :selected yas-good-grace]
688 ["Load snippets..." yas-load-directory
689 :help "Load snippets from a specific directory"]
690 ["Reload everything" yas-reload-all
691 :help "Cleanup stuff, reload snippets, rebuild menus"]
693 :help "Display some information about YASsnippet"])))
695 ;; Now for the stuff that has direct keybindings
697 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
698 (define-key map "\C-c&\C-n" 'yas-new-snippet)
699 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
702 (defvar yas-minor-mode-map (yas--init-minor-keymap)
703 "The keymap used when `yas-minor-mode' is active.")
705 (defun yas--trigger-key-reload (&optional unbind-key)
706 "Rebind `yas-expand' to the new value of `yas-trigger-key'.
708 With optional UNBIND-KEY, try to unbind that key from
709 `yas-minor-mode-map'."
710 (when (and unbind-key
712 (not (string= unbind-key "")))
713 (define-key yas-minor-mode-map (read-kbd-macro unbind-key) nil))
714 (when (and yas-trigger-key
715 (stringp yas-trigger-key)
716 (not (string= yas-trigger-key "")))
717 (define-key yas-minor-mode-map (read-kbd-macro yas-trigger-key) 'yas-expand)))
719 (defvar yas--tables (make-hash-table)
720 "A hash table of mode symbols to `yas--table' objects.")
722 (defvar yas--parents (make-hash-table)
723 "A hash table of mode symbols do lists of direct parent mode symbols.
725 This list is populated when reading the \".yas-parents\" files
726 found when traversing snippet directories with
727 `yas-load-directory'.
729 There might be additionalal parenting information stored in the
730 `derived-mode-parent' property of some mode symbols, but that is
733 (defvar yas--direct-keymaps (list)
734 "Keymap alist supporting direct snippet keybindings.
736 This variable is is placed in `emulation-mode-map-alists'.
738 Its elements looks like (TABLE-NAME . KEYMAP). They're
739 instantiated on `yas-reload-all' but KEYMAP is added to only when
740 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
741 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
742 defined direct keybindings to the command
743 `yas-expand-from-keymap' which then which snippet to expand.")
745 (defun yas-direct-keymaps-reload ()
746 "Force reload the direct keybinding for active snippet tables."
748 (setq yas--direct-keymaps nil)
749 (maphash #'(lambda (name table)
750 (push (cons (intern (format "yas--direct-%s" name))
751 (yas--table-direct-keymap table))
752 yas--direct-keymaps))
755 (defun yas--modes-to-activate ()
756 "Compute list of mode symbols that are active for `yas-expand'
758 (let ((modes-to-activate (list major-mode))
760 (while (setq mode (get mode 'derived-mode-parent))
761 (push mode modes-to-activate))
762 (dolist (mode (yas-extra-modes))
763 (push mode modes-to-activate))
765 (append modes-to-activate
766 (mapcan #'(lambda (mode)
767 (yas--all-parents mode))
768 modes-to-activate)))))
770 (defvar yas-minor-mode-hook nil
771 "Hook run when yas-minor-mode is turned on")
774 (define-minor-mode yas-minor-mode
775 "Toggle YASnippet mode.
777 When YASnippet mode is enabled, the `yas-trigger-key' key expands
778 snippets of code depending on the major mode.
780 With no argument, this command toggles the mode.
781 positive prefix argument turns on the mode.
782 Negative prefix argument turns off the mode.
784 You can customize the key through `yas-trigger-key'.
787 \\{yas-minor-mode-map}"
789 ;; The indicator for the mode line.
792 (cond (yas-minor-mode
793 ;; Reload the trigger key
795 (yas--trigger-key-reload)
796 ;; Install the direct keymaps in `emulation-mode-map-alists'
797 ;; (we use `add-hook' even though it's not technically a hook,
798 ;; but it works). Then define variables named after modes to
799 ;; index `yas--direct-keymaps'.
801 ;; Also install the post-command-hook.
803 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
804 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
805 ;; Set the `yas--direct-%s' vars for direct keymap expansion
807 (dolist (mode (yas--modes-to-activate))
808 (let ((name (intern (format "yas--direct-%s" mode))))
809 (set-default name nil)
810 (set (make-local-variable name) t)))
813 (yas--load-pending-jits))
815 ;; Uninstall the direct keymaps and the post-command hook
817 (remove-hook 'post-command-hook 'yas--post-command-handler t)
818 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
820 (defvar yas--dont-activate '(minibufferp)
821 "If non-nil don't let `yas-minor-mode-on' active yas for this buffer.
823 If a function, then its result is used.
825 If a list of functions, then all functions must return nil to
826 activate yas for this buffer.
828 `yas-minor-mode-on' is usually called by `yas-global-mode' so
829 this effectively lets you define exceptions to the \"global\"
830 behaviour. Can also be a function of zero arguments.")
831 (make-variable-buffer-local 'yas--dont-activate)
833 (defun yas-minor-mode-on ()
834 "Turn on YASnippet minor mode.
836 Do this unless `yas--dont-activate' is truish "
838 (unless (cond ((functionp yas--dont-activate)
839 (funcall yas--dont-activate))
840 ((consp yas--dont-activate)
841 (some #'funcall yas--dont-activate))
842 (yas--dont-activate))
843 ;; Load all snippets definitions unless we still don't have a
844 ;; root-directory or some snippets have already been loaded.
849 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
853 (defun yas--global-mode-reload-with-jit-maybe ()
854 (when yas-global-mode (yas-reload-all)))
856 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
858 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
861 (defvar yas--font-lock-keywords
862 (append '(("^#.*$" . font-lock-comment-face))
863 lisp-font-lock-keywords
864 lisp-font-lock-keywords-1
865 lisp-font-lock-keywords-2
867 (0 font-lock-keyword-face)
868 (1 font-lock-string-face t))
870 (0 font-lock-keyword-face)
871 (1 font-lock-warning-face t))
872 ("${" font-lock-keyword-face)
873 ("$[0-9]+?" font-lock-preprocessor-face)
874 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
876 (0 font-lock-keyword-face)))))
878 (defun yas--init-major-keymap ()
879 (let ((map (make-sparse-keymap)))
880 (easy-menu-define nil
882 "Menu used when snippet-mode is active."
884 (mapcar #'(lambda (ent)
886 (define-key map (third ent) (second ent)))
887 (vector (first ent) (second ent) t))
889 (list "Load this snippet" 'yas-load-snippet-buffer "\C-c\C-c")
890 (list "Try out this snippet" 'yas-tryout-snippet "\C-c\C-t")))))
893 (defvar snippet-mode-map
894 (yas--init-major-keymap)
895 "The keymap used when `snippet-mode' is active")
898 (define-derived-mode snippet-mode text-mode "Snippet"
899 "A mode for editing yasnippets"
900 (setq font-lock-defaults '(yas--font-lock-keywords))
901 (set (make-local-variable 'require-final-newline) nil)
902 (set (make-local-variable 'comment-start) "#")
903 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
907 ;;; Internal structs for template management
909 (defstruct (yas--template (:constructor yas--make-blank-template))
910 "A template for a snippet."
920 group ;; as dictated by the #group: directive or .yas-make-groups
921 perm-group ;; as dictated by `yas-define-menu'
925 (defun yas--populate-template (template &rest args)
926 "Helper function to populate a template with properties"
930 (position (intern (substring (symbol-name (car args)) 1))
931 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
933 (setq args (cddr args)))
936 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
937 "A table to store snippets for a particular mode.
939 Has the following fields:
943 A symbol name normally corresponding to a major mode, but can
944 also be a pseudo major-mode to be referenced in
945 `yas-extra-modes', for example.
949 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
950 a string or a vector, where the former is the snippet's trigger
951 and the latter means it's a direct keybinding. NAMEHASH is yet
952 another hash of (NAME . TEMPLATE) where NAME is the snippet's
953 name and TEMPLATE is a `yas--template' object.
955 `yas--table-direct-keymap'
957 A keymap for the snippets in this table that have direct
958 keybindings. This is kept in sync with the keyhash, i.e., all
959 the elements of the keyhash that are vectors appear here as
960 bindings to `yas-expand-from-keymap'.
962 `yas--table-uuidhash'
964 A hash table mapping snippets uuid's to the same `yas--template'
965 objects. A snippet uuid defaults to the snippet's name.
968 (hash (make-hash-table :test 'equal))
969 (uuidhash (make-hash-table :test 'equal))
971 (direct-keymap (make-sparse-keymap)))
973 (defun yas--get-template-by-uuid (mode uuid)
974 "Find the snippet template in MODE by its UUID."
975 (let* ((table (gethash mode yas--tables mode)))
977 (gethash uuid (yas--table-uuidhash table)))))
979 ;; Apropos storing/updating in TABLE, this works in two steps:
981 ;; 1. `yas--remove-template-by-uuid' removes any
982 ;; keyhash-namehash-template mappings from TABLE, grabing the
983 ;; snippet by its uuid. Also removes mappings from TABLE's
984 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
985 ;; of potentially stale menu bindings right?.)
987 ;; 2. `yas--add-template' adds this all over again.
989 ;; Create a new or add to an existing keyhash-namehash mapping.
991 ;; For reference on understanding this, consider three snippet
994 ;; A: # name: The Foo
996 ;; # binding: C-c M-l
998 ;; B: # name: Mrs Foo
1001 ;; C: # name: The Bar
1002 ;; # binding: C-c M-l
1007 ;; keyhash namehashes(3) yas--template structs(4)
1008 ;; -----------------------------------------------------
1011 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1012 ;; "Mrs Foo" ---> [yas--template B] |
1014 ;; [C-c M-l] ---> "The Foo" -------------------------/
1015 ;; "The Bar" ---> [yas--template C]
1017 ;; "baz" ---> "Baz" ---> [yas--template D]
1019 ;; Additionally, since uuid defaults to the name, we have a
1020 ;; `yas--table-uuidhash' for TABLE
1022 ;; uuidhash yas--template structs
1023 ;; -------------------------------
1024 ;; "The Foo" ---> [yas--template A]
1025 ;; "Mrs Foo" ---> [yas--template B]
1026 ;; "The Bar" ---> [yas--template C]
1027 ;; "Baz" ---> [yas--template D]
1029 ;; FIXME: the more I look at this data-structure the more I think I'm
1030 ;; stupid. There has to be an easier way (but beware lots of code
1031 ;; depends on this).
1033 (defun yas--remove-template-by-uuid (table uuid)
1034 "Remove from TABLE a template identified by UUID."
1035 (let ((template (gethash uuid (yas--table-uuidhash table))))
1037 (let* ((name (yas--template-name template))
1039 ;; Remove the name from each of the targeted namehashes
1041 (maphash #'(lambda (k v)
1042 (let ((template (gethash name v)))
1044 (eq uuid (yas--template-uuid template)))
1046 (when (zerop (hash-table-count v))
1047 (push k empty-keys)))))
1048 (yas--table-hash table))
1049 ;; Remove the namehash themselves if they've become empty
1051 (dolist (key empty-keys)
1053 (define-key (yas--table-direct-keymap table) key nil))
1054 (remhash key (yas--table-hash table)))
1056 ;; Finally, remove the uuid from the uuidhash
1058 (remhash uuid (yas--table-uuidhash table))))))
1060 (defun yas--add-template (table template)
1061 "Store in TABLE the snippet template TEMPLATE.
1063 KEY can be a string (trigger key) of a vector (direct
1065 (let ((name (yas--template-name template))
1066 (key (yas--template-key template))
1067 (keybinding (yas--template-keybinding template))
1068 (menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1069 (dolist (k (remove nil (list key keybinding)))
1073 (yas--table-hash table))
1075 (make-hash-table :test 'equal)
1076 (yas--table-hash table))))
1078 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1080 ;; Update TABLE's `yas--table-uuidhash'
1081 (puthash (yas--template-uuid template)
1083 (yas--table-uuidhash table))))
1085 (defun yas--update-template (table template)
1086 "Add or update TEMPLATE in TABLE.
1088 Also takes care of adding and updating to the associated menu."
1089 ;; Remove from table by uuid
1091 (yas--remove-template-by-uuid table (yas--template-uuid template))
1092 ;; Add to table again
1094 (yas--add-template table template)
1095 ;; Take care of the menu
1098 (yas--update-template-menu table template)))
1100 (defun yas--update-template-menu (table template)
1101 "Update every menu-related for TEMPLATE"
1102 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1103 (key (yas--template-key template))
1104 (keybinding (yas--template-keybinding template)))
1105 ;; The snippet might have changed name or keys, so update
1106 ;; user-visible strings
1108 (unless (eq (cdr menu-binding-pair) :none)
1109 ;; the menu item name
1111 (setf (cadar menu-binding-pair) (yas--template-name template))
1112 ;; the :keys information (also visible to the user)
1113 (setf (getf (cdr (car menu-binding-pair)) :keys)
1114 (or (and keybinding (key-description keybinding))
1115 (and key (concat key yas-trigger-symbol))))))
1116 (unless (yas--template-menu-managed-by-yas-define-menu template)
1118 (yas--menu-keymap-get-create (yas--table-mode table)
1119 (mapcar #'yas--table-mode
1120 (yas--table-parents table))))
1121 (group (yas--template-group template)))
1122 ;; Remove from menu keymap
1124 (assert menu-keymap)
1125 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1127 ;; Add necessary subgroups as necessary.
1129 (dolist (subgroup group)
1130 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1131 (unless (and subgroup-keymap
1132 (keymapp subgroup-keymap))
1133 (setq subgroup-keymap (make-sparse-keymap))
1134 (define-key menu-keymap (vector (make-symbol subgroup))
1135 `(menu-item ,subgroup ,subgroup-keymap)))
1136 (setq menu-keymap subgroup-keymap)))
1138 ;; Add this entry to the keymap
1140 (define-key menu-keymap
1141 (vector (make-symbol (yas--template-uuid template)))
1142 (car (yas--template-menu-binding-pair template))))))
1144 (defun yas--namehash-templates-alist (namehash)
1146 (maphash #'(lambda (k v)
1147 (push (cons k v) alist))
1151 (defun yas--fetch (table key)
1152 "Fetch templates in TABLE by KEY.
1154 Return a list of cons (NAME . TEMPLATE) where NAME is a
1155 string and TEMPLATE is a `yas--template' structure."
1156 (let* ((keyhash (yas--table-hash table))
1157 (namehash (and keyhash (gethash key keyhash))))
1159 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1162 ;;; Filtering/condition logic
1164 (defun yas--eval-condition (condition)
1171 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1175 (defun yas--filter-templates-by-condition (templates)
1176 "Filter the templates using the applicable condition.
1178 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1179 string and TEMPLATE is a `yas--template' structure.
1181 This function implements the rules described in
1182 `yas-buffer-local-condition'. See that variables documentation."
1183 (let ((requirement (yas--require-template-specific-condition-p)))
1184 (if (eq requirement 'always)
1186 (remove-if-not #'(lambda (pair)
1187 (yas--template-can-expand-p
1188 (yas--template-condition (cdr pair)) requirement))
1191 (defun yas--require-template-specific-condition-p ()
1192 "Decides if this buffer requests/requires snippet-specific
1193 conditions to filter out potential expansions."
1194 (if (eq 'always yas-buffer-local-condition)
1196 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1197 (yas--eval-condition yas-buffer-local-condition))
1198 yas-buffer-local-condition)))
1199 (when local-condition
1200 (if (eq local-condition t)
1202 (and (consp local-condition)
1203 (eq 'require-snippet-condition (car local-condition))
1204 (symbolp (cdr local-condition))
1205 (cdr local-condition)))))))
1207 (defun yas--template-can-expand-p (condition requirement)
1208 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1209 (let* ((result (or (null condition)
1210 (yas--eval-condition condition))))
1211 (cond ((eq requirement t)
1214 (eq requirement result)))))
1216 (defun yas--all-parents (mode)
1217 "Returns a list of all parent modes of MODE"
1218 (let ((parents (gethash mode yas--parents)))
1220 (mapcan #'yas--all-parents parents))))
1222 (defun yas--table-templates (table)
1225 (maphash #'(lambda (key namehash)
1226 (maphash #'(lambda (name template)
1227 (push (cons name template) acc))
1229 (yas--table-hash table))
1230 (yas--filter-templates-by-condition acc))))
1232 (defun yas--current-key ()
1233 "Get the key under current position. A key is used to find
1234 the template of a snippet in the current snippet-table."
1235 (let ((start (point))
1237 (syntaxes yas-key-syntaxes)
1241 (while (and (not done) syntaxes)
1242 (setq syntax (car syntaxes))
1243 (setq syntaxes (cdr syntaxes))
1245 (skip-syntax-backward syntax)
1246 (setq start (point)))
1248 (mapcan #'(lambda (table)
1249 (yas--fetch table (buffer-substring-no-properties start end)))
1250 (yas--get-snippet-tables)))
1259 (defun yas--table-all-keys (table)
1262 (maphash #'(lambda (key namehash)
1263 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1265 (yas--table-hash table))
1268 (defun yas--table-mode (table)
1269 (intern (yas--table-name table)))
1272 ;;; Internal functions:
1274 (defun yas--real-mode? (mode)
1275 "Try to find out if MODE is a real mode. The MODE bound to
1276 a function (like `c-mode') is considered real mode. Other well
1277 known mode like `ruby-mode' which is not part of Emacs might
1278 not bound to a function until it is loaded. So yasnippet keeps
1279 a list of modes like this to help the judgement."
1281 (find mode yas--known-modes)))
1283 (defun yas--eval-lisp (form)
1284 "Evaluate FORM and convert the result to string."
1285 (let ((retval (catch 'yas--exception
1291 (let ((result (eval form)))
1293 (format "%s" result))))))
1294 (error (if yas-good-grace
1295 (yas--format "elisp error! %s" (error-message-string err))
1296 (error (yas--format "elisp error: %s"
1297 (error-message-string err)))))))))
1298 (when (and (consp retval)
1299 (eq 'yas--exception (car retval)))
1300 (error (cdr retval)))
1303 (defun yas--eval-lisp-no-saves (form)
1306 (error (if yas-good-grace
1307 (yas--format "elisp error! %s" (error-message-string err))
1308 (error (yas--format "elisp error: %s"
1309 (error-message-string err)))))))
1311 (defun yas--read-lisp (string &optional nil-on-error)
1312 "Read STRING as a elisp expression and return it.
1314 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1315 return an expression that when evaluated will issue an error."
1318 (error (and (not nil-on-error)
1319 `(error (error-message-string ,err))))))
1321 (defun yas--read-keybinding (keybinding)
1322 "Read KEYBINDING as a snippet keybinding, return a vector."
1323 (when (and keybinding
1324 (not (string-match "keybinding" keybinding)))
1326 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1328 (read-kbd-macro keybinding 'need-vector))))
1331 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1332 keybinding (error-message-string err))
1335 (defvar yas-extra-modes nil
1336 "If non-nil, also lookup snippets for this/these modes.
1338 Can be a symbol or a list of symbols.
1340 This variable probably makes more sense as buffer-local, so
1341 ensure your use `make-local-variable' when you set it.")
1342 (defun yas-extra-modes ()
1343 (if (listp yas-extra-modes) yas-extra-modes (list yas-extra-modes)))
1344 (defvaralias 'yas/mode-symbol 'yas-extra-modes)
1346 (defun yas--table-get-create (mode)
1347 "Get or create the snippet table corresponding to MODE."
1348 (let ((table (gethash mode
1351 (setq table (yas--make-snippet-table (symbol-name mode)))
1352 (puthash mode table yas--tables)
1353 (push (cons (intern (format "yas--direct-%s" mode))
1354 (yas--table-direct-keymap table))
1355 yas--direct-keymaps))
1358 (defun yas--get-snippet-tables ()
1359 "Get snippet tables for current buffer.
1361 Return a list of `yas--table' objects. The list of modes to
1362 consider is returned by `yas--modes-to-activate'"
1364 (mapcar #'(lambda (mode-name)
1365 (gethash mode-name yas--tables))
1366 (yas--modes-to-activate))))
1368 (defun yas--menu-keymap-get-create (mode &optional parents)
1369 "Get or create the menu keymap for MODE and its PARENTS.
1371 This may very well create a plethora of menu keymaps and arrange
1372 them all in `yas--menu-table'"
1373 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1374 (puthash mode (make-sparse-keymap) yas--menu-table))))
1375 (mapc #'yas--menu-keymap-get-create parents)
1376 (define-key yas--minor-mode-menu (vector mode)
1377 `(menu-item ,(symbol-name mode) ,menu-keymap
1378 :visible (yas--show-menu-p ',mode)))
1381 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1382 ;;; Template-related and snippet loading functions
1384 (defun yas--parse-template (&optional file)
1385 "Parse the template in the current buffer.
1387 Optional FILE is the absolute file name of the file being
1390 Optional GROUP is the group where the template is to go,
1391 otherwise we attempt to calculate it from FILE.
1393 Return a snippet-definition, i.e. a list
1395 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1397 If the buffer contains a line of \"# --\" then the contents above
1398 this line are ignored. Directives can set most of these with the syntax:
1400 # directive-name : directive-value
1402 Here's a list of currently recognized directives:
1413 (goto-char (point-min))
1414 (let* ((type 'snippet)
1416 (file-name-nondirectory file)))
1422 (yas--calculate-group file)))
1426 (if (re-search-forward "^# --\n" nil t)
1427 (progn (setq template
1428 (buffer-substring-no-properties (point)
1430 (setq bound (point))
1431 (goto-char (point-min))
1432 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1433 (when (string= "uuid" (match-string-no-properties 1))
1434 (setq uuid (match-string-no-properties 2)))
1435 (when (string= "type" (match-string-no-properties 1))
1436 (setq type (if (string= "command" (match-string-no-properties 2))
1439 (when (string= "key" (match-string-no-properties 1))
1440 (setq key (match-string-no-properties 2)))
1441 (when (string= "name" (match-string-no-properties 1))
1442 (setq name (match-string-no-properties 2)))
1443 (when (string= "condition" (match-string-no-properties 1))
1444 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1445 (when (string= "group" (match-string-no-properties 1))
1446 (setq group (match-string-no-properties 2)))
1447 (when (string= "expand-env" (match-string-no-properties 1))
1448 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1450 (when (string= "binding" (match-string-no-properties 1))
1451 (setq binding (match-string-no-properties 2)))))
1453 (buffer-substring-no-properties (point-min) (point-max))))
1454 (unless (or key binding)
1455 (setq key (and file (file-name-nondirectory file))))
1456 (when (eq type 'command)
1457 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1459 (setq group (split-string group "\\.")))
1460 (list key template name condition group expand-env file binding uuid)))
1462 (defun yas--calculate-group (file)
1463 "Calculate the group for snippet file path FILE."
1464 (let* ((dominating-dir (locate-dominating-file file
1465 ".yas-make-groups"))
1466 (extra-path (and dominating-dir
1467 (replace-regexp-in-string (concat "^"
1468 (expand-file-name dominating-dir))
1470 (expand-file-name file))))
1471 (extra-dir (and extra-path
1472 (file-name-directory extra-path)))
1473 (group (and extra-dir
1474 (replace-regexp-in-string "/"
1476 (directory-file-name extra-dir)))))
1479 (defun yas--subdirs (directory &optional filep)
1480 "Return subdirs or files of DIRECTORY according to FILEP."
1481 (remove-if (lambda (file)
1482 (or (string-match "^\\."
1483 (file-name-nondirectory file))
1484 (string-match "^#.*#$"
1485 (file-name-nondirectory file))
1487 (file-name-nondirectory file))
1489 (file-directory-p file)
1490 (not (file-directory-p file)))))
1491 (directory-files directory t)))
1493 (defun yas--make-menu-binding (template)
1494 (let ((mode (yas--table-mode (yas--template-table template))))
1495 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1497 (defun yas--expand-or-visit-from-menu (mode uuid)
1498 (let* ((table (yas--table-get-create mode))
1499 (yas--current-template (and table
1500 (gethash uuid (yas--table-uuidhash table)))))
1501 (when yas--current-template
1502 (if yas-visit-from-menu
1503 (yas--visit-snippet-file-1 yas--current-template)
1504 (let ((where (if (region-active-p)
1505 (cons (region-beginning) (region-end))
1506 (cons (point) (point)))))
1507 (yas-expand-snippet (yas--template-content yas--current-template)
1510 (yas--template-expand-env yas--current-template)))))))
1512 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1513 ;; Popping up for keys and templates
1515 (defvar yas--x-pretty-prompt-templates nil
1516 "If non-nil, attempt to prompt for templates like TextMate.")
1519 (defun yas--prompt-for-template (templates &optional prompt)
1520 "Interactively choose a template from the list TEMPLATES.
1522 TEMPLATES is a list of `yas--template'."
1525 (sort templates #'(lambda (t1 t2)
1526 (< (length (yas--template-name t1))
1527 (length (yas--template-name t2))))))
1528 (if yas--x-pretty-prompt-templates
1529 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1530 (some #'(lambda (fn)
1531 (funcall fn (or prompt "Choose a snippet: ")
1533 #'yas--template-name))
1534 yas-prompt-functions))))
1536 (defun yas--prompt-for-keys (keys &optional prompt)
1537 "Interactively choose a template key from the list KEYS."
1539 (some #'(lambda (fn)
1540 (funcall fn (or prompt "Choose a snippet key: ") keys))
1541 yas-prompt-functions)))
1543 (defun yas--prompt-for-table (tables &optional prompt)
1545 (some #'(lambda (fn)
1546 (funcall fn (or prompt "Choose a snippet table: ")
1549 yas-prompt-functions)))
1551 (defun yas-x-prompt (prompt choices &optional display-fn)
1552 "Display choices in a x-window prompt."
1553 ;; FIXME: HACK: if we notice that one of the objects in choices is
1554 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1556 ;; This would be better implemented by passing CHOICES as a
1557 ;; strucutred tree rather than a list. Modifications would go as far
1558 ;; up as `yas--all-templates' I think.
1560 (when (and window-system choices)
1562 (let (menu d) ;; d for display
1564 (setq d (or (and display-fn (funcall display-fn c))
1567 (push (cons (concat " " d) c) menu))
1569 (push (car d) menu))))
1570 (setq menu (list prompt (push "title" menu)))
1571 (x-popup-menu (if (fboundp 'posn-at-point)
1572 (let ((x-y (posn-x-y (posn-at-point (point)))))
1573 (list (list (+ (car x-y) 10)
1581 (defun yas--x-pretty-prompt-templates (prompt templates)
1582 "Display TEMPLATES, grouping neatly by table name."
1583 (let ((organized (make-hash-table :test #'equal))
1587 (dolist (tl templates)
1588 (puthash (yas--template-table tl)
1590 (gethash (yas--template-table tl) organized))
1592 (setq more-than-one-table (> (hash-table-count organized) 1))
1593 (setq prefix (if more-than-one-table
1595 (if more-than-one-table
1596 (maphash #'(lambda (table templates)
1597 (push (yas--table-name table) menu)
1598 (dolist (tl templates)
1599 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1600 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1602 (setq menu (nreverse menu))
1603 (or (x-popup-menu (if (fboundp 'posn-at-point)
1604 (let ((x-y (posn-x-y (posn-at-point (point)))))
1605 (list (list (+ (car x-y) 10)
1609 (list prompt (push "title" menu)))
1612 (defun yas-ido-prompt (prompt choices &optional display-fn)
1613 (when (and (fboundp 'ido-completing-read)
1614 (or (>= emacs-major-version 24)
1616 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1618 (eval-when-compile (require 'dropdown-list nil t))
1619 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1620 (when (featurep 'dropdown-list)
1621 (let (formatted-choices
1625 (dolist (choice choices)
1626 (setq d (or (and display-fn (funcall display-fn choice))
1629 (push d formatted-choices)
1630 (push choice filtered-choices)))
1632 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1634 (nth n filtered-choices)
1637 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1638 (let (formatted-choices
1642 (completion-fn (or completion-fn
1643 #'completing-read)))
1644 (dolist (choice choices)
1645 (setq d (or (and display-fn (funcall display-fn choice))
1648 (push d formatted-choices)
1649 (push choice filtered-choices)))
1650 (setq chosen (and formatted-choices
1651 (funcall completion-fn prompt
1657 (let ((position (or (and chosen
1658 (position chosen formatted-choices :test #'string=))
1660 (nth position filtered-choices))))
1662 (defun yas-no-prompt (prompt choices &optional display-fn)
1665 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1666 ;; Loading snippets from files
1668 (defun yas--load-yas-setup-file (file)
1669 (load file 'noerror))
1671 (defun yas-load-directory (top-level-dir &optional use-jit)
1672 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1674 Below TOP-LEVEL-DIR each directory should be a mode name.
1676 Optional USE-JIT use jit-loading of snippets."
1677 (interactive "DSelect the root directory: ")
1678 (unless yas-snippet-dirs
1679 (setq yas-snippet-dirs top-level-dir))
1680 (dolist (dir (yas--subdirs top-level-dir))
1681 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1682 (concat dir "/dummy")))
1683 (mode-sym (car major-mode-and-parents))
1684 (parents (cdr major-mode-and-parents)))
1685 ;; Attention: The parents and the menus are already defined
1686 ;; here, even if the snippets are later jit-loaded.
1688 ;; * We need to know the parents at this point since entering a
1689 ;; given mode should jit load for its parents
1690 ;; immediately. This could be reviewed, the parents could be
1691 ;; discovered just-in-time-as well
1693 ;; * We need to create the menus here to support the `full'
1694 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1696 (yas--define-parents mode-sym parents)
1697 (yas--menu-keymap-get-create mode-sym)
1698 (let ((form `(yas--load-directory-1 ,dir
1702 (yas--schedule-jit mode-sym form)
1704 (when (interactive-p)
1705 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1707 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1708 "Recursively load snippet templates from DIRECTORY."
1709 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1710 (if (and (not no-compiled-snippets)
1711 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1712 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1713 (yas--message 2 "Loading snippet files from %s" directory)
1714 (yas--load-directory-2 directory mode-sym))))
1716 (defun yas--load-directory-2 (directory mode-sym)
1717 ;; Load .yas-setup.el files wherever we find them
1719 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1720 (let* ((default-directory directory)
1722 ;; load the snippet files
1725 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1726 (when (file-readable-p file)
1727 (insert-file-contents file nil nil nil t)
1728 (push (yas--parse-template file)
1731 (yas-define-snippets mode-sym
1733 ;; now recurse to a lower level
1735 (dolist (subdir (yas--subdirs directory))
1736 (yas--load-directory-2 subdir
1739 (defun yas--load-snippet-dirs (&optional nojit)
1740 "Reload the directories listed in `yas-snippet-dirs' or
1741 prompt the user to select one."
1743 (if yas-snippet-dirs
1744 (dolist (directory (reverse (yas-snippet-dirs)))
1745 (cond ((file-directory-p directory)
1746 (yas-load-directory directory (not nojit))
1748 (yas--message 3 "Loaded %s" directory)
1749 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1751 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1752 (call-interactively 'yas-load-directory))
1755 (defun yas-reload-all (&optional interactive)
1756 "Reload all snippets and rebuild the YASnippet menu.
1758 When called interactively force immediate reload of all known
1759 snippets under `yas-snippet-dirs', otherwise use just-in-time
1764 (snippet-editing-buffers
1765 (remove-if-not #'(lambda (buffer)
1766 (with-current-buffer buffer yas--editing-template))
1768 ;; Warn if there are buffers visiting snippets, since reloading will break
1769 ;; any on-line editing of those buffers.
1771 (when snippet-editing-buffers
1773 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1774 (mapc #'kill-buffer snippet-editing-buffers)
1775 (yas--message 1 "Aborted reload...")
1777 ;; in a non-interactive use, at least set
1778 ;; `yas--editing-template' to nil, make it guess it next time around
1779 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1781 ;; Empty all snippet tables, parenting info and all menu tables
1783 (setq yas--tables (make-hash-table))
1784 (setq yas--parents (make-hash-table))
1785 (setq yas--menu-table (make-hash-table))
1787 ;; Cancel all pending 'yas--scheduled-jit-loads'
1789 (setq yas--scheduled-jit-loads (make-hash-table))
1791 ;; Init the `yas-minor-mode-map', taking care not to break the
1794 (setcdr yas-minor-mode-map (cdr (yas--init-minor-keymap)))
1796 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1797 ;; the user to select one.
1799 (setq errors (yas--load-snippet-dirs interactive))
1800 ;; Reload the direct keybindings
1802 (yas-direct-keymaps-reload)
1803 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1805 (yas--trigger-key-reload)
1807 (yas--message 3 "Reloaded everything%s...%s."
1808 (if interactive "" " (snippets will load just-in-time)")
1809 (if errors " (some errors, check *Messages*)" "")))))
1811 (defun yas--load-pending-jits ()
1812 (when yas-minor-mode
1813 (dolist (mode (yas--modes-to-activate))
1814 (let ((forms (gethash mode yas--scheduled-jit-loads)))
1815 (dolist (form forms)
1816 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1818 (remhash mode yas--scheduled-jit-loads)))))
1820 ;; (when (<= emacs-major-version 22)
1821 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1823 (defun yas--quote-string (string)
1824 "Escape and quote STRING.
1825 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1827 (replace-regexp-in-string "[\\\"]"
1832 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1833 ;;; Snippet compilation function
1835 (defun yas--initialize ()
1836 "For backward compatibility, enable `yas-minor-mode' globally"
1837 (yas-global-mode 1))
1839 (defun yas-compile-directory (top-level-dir)
1840 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1842 This works by stubbing a few functions, then calling
1843 `yas-load-directory'."
1844 (interactive "DTop level snippet directory?")
1845 (flet ((yas--load-yas-setup-file
1847 (let ((elfile (concat file ".el")))
1848 (when (file-exists-p elfile)
1849 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1850 (insert-file-contents elfile)
1853 (yas-define-snippets
1855 (insert ";;; Snippet definitions:\n;;;\n")
1856 (let ((literal-snippets (list))
1858 (dolist (snippet snippets)
1859 (let ((key (first snippet))
1860 (template-content (second snippet))
1861 (name (third snippet))
1862 (condition (fourth snippet))
1863 (group (fifth snippet))
1864 (expand-env (sixth snippet))
1865 (file nil) ;; (seventh snippet)) ;; omit on purpose
1866 (binding (eighth snippet))
1867 (uuid (ninth snippet)))
1878 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1880 (yas--load-directory-1
1881 (dir mode parents &rest ignore)
1882 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1883 (with-temp-file output-file
1884 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1885 (yas--load-directory-2 dir mode)
1886 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1887 (yas-load-directory top-level-dir nil)))
1889 (defun yas-recompile-all ()
1890 "Compile every dir in `yas-snippet-dirs'."
1892 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1898 (defvar yas--scheduled-jit-loads (make-hash-table)
1899 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1901 (defun yas--schedule-jit (mode form)
1904 (gethash mode yas--scheduled-jit-loads))
1905 yas--scheduled-jit-loads))
1908 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1909 ;;; Some user level functions
1914 (message (concat "yasnippet (version "
1916 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1918 (defun yas--define-parents (mode parents)
1919 "Add PARENTS to the list of MODE's parents"
1920 (puthash mode (remove-duplicates
1922 (gethash mode yas--parents)))
1925 (defun yas-define-snippets (mode snippets)
1926 "Define SNIPPETS for MODE.
1928 SNIPPETS is a list of snippet definitions, each taking the
1931 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1933 Within these, only KEY and TEMPLATE are actually mandatory.
1935 TEMPLATE might be a lisp form or a string, depending on whether
1936 this is a snippet or a snippet-command.
1938 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1939 been `yas--read-lisp'-ed and will eventually be
1940 `yas--eval-lisp'-ed.
1942 The remaining elements are strings.
1944 FILE is probably of very little use if you're programatically
1947 UUID is the snippets \"unique-id\". Loading a second snippet file
1948 with the same uuid replaced the previous snippet.
1950 You can use `yas--parse-template' to return such lists based on
1951 the current buffers contents."
1952 (let ((snippet-table (yas--table-get-create mode))
1954 (dolist (snippet snippets)
1955 (setq template (yas-define-snippets-1 snippet
1959 (defun yas-define-snippets-1 (snippet snippet-table)
1960 "Helper for `yas-define-snippets'."
1961 ;; X) Calculate some more defaults on the values returned by
1962 ;; `yas--parse-template'.
1964 (let* ((file (seventh snippet))
1966 (name (or (third snippet)
1968 (file-name-directory file))))
1969 (condition (fourth snippet))
1970 (group (fifth snippet))
1971 (keybinding (yas--read-keybinding (eighth snippet)))
1972 (uuid (or (ninth snippet)
1974 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1975 (yas--make-blank-template))))
1976 ;; X) populate the template object
1978 (yas--populate-template template
1979 :table snippet-table
1981 :content (second snippet)
1984 :condition condition
1985 :expand-env (sixth snippet)
1986 :file (seventh snippet)
1987 :keybinding keybinding
1989 ;; X) Update this template in the appropriate table. This step
1990 ;; also will take care of adding the key indicators in the
1991 ;; templates menu entry, if any
1993 (yas--update-template snippet-table template)
1994 ;; X) Return the template
2000 ;;; Apropos snippet menu:
2002 ;; The snippet menu keymaps are store by mode in hash table called
2003 ;; `yas--menu-table'. They are linked to the main menu in
2004 ;; `yas--menu-keymap-get-create' and are initially created empty,
2005 ;; reflecting the table hierarchy.
2007 ;; They can be populated in two mutually exclusive ways: (1) by
2008 ;; reading `yas--template-group', which in turn is populated by the "#
2009 ;; group:" directives of the snippets or the ".yas-make-groups" file
2010 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2011 ;; menu structure based on snippets uuids.
2013 ;; Both situations are handled in `yas--update-template-menu', which
2014 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2015 ;; that can tell between the two situations.
2019 ;; * if `yas-define-menu' is used it must run before
2020 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2021 ;; duplicate entries. The `yas--template' objects are created in
2022 ;; `yas-define-menu', holding nothing but the menu entry,
2023 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2024 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2025 ;; part is then stored in the menu keymap itself which make the item
2026 ;; appear to the user. These limitations could probably be revised.
2028 ;; * The `yas--template-perm-group' slot is only used in
2029 ;; `yas-describe-tables'.
2031 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2032 "Get TEMPLATE's menu binding or assign it a new one.
2034 TYPE may be `:stay', signalling this menu binding should be
2035 static in the menu."
2036 (or (yas--template-menu-binding-pair template)
2037 (let ((key (yas--template-key template))
2038 (keybinding (yas--template-keybinding template)))
2039 (setf (yas--template-menu-binding-pair template)
2040 (cons `(menu-item ,(or (yas--template-name template)
2041 (yas--template-uuid template))
2042 ,(yas--make-menu-binding template)
2045 (defun yas--template-menu-managed-by-yas-define-menu (template)
2046 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2047 (cdr (yas--template-menu-binding-pair template)))
2050 (defun yas--show-menu-p (mode)
2051 (cond ((eq yas-use-menu 'abbreviate)
2053 (mapcar #'(lambda (table)
2054 (yas--table-mode table))
2055 (yas--get-snippet-tables))))
2056 ((eq yas-use-menu 'full)
2058 ((eq yas-use-menu t)
2061 (defun yas--delete-from-keymap (keymap uuid)
2062 "Recursively delete items with UUID from KEYMAP and its submenus."
2064 ;; XXX: This used to skip any submenus named \"parent mode\"
2066 ;; First of all, recursively enter submenus, i.e. the tree is
2067 ;; searched depth first so that stale submenus can be found in the
2070 (mapc #'(lambda (item)
2071 (when (and (listp (cdr item))
2072 (keymapp (third (cdr item))))
2073 (yas--delete-from-keymap (third (cdr item)) uuid)))
2075 ;; Set the uuid entry to nil
2077 (define-key keymap (vector (make-symbol uuid)) nil)
2078 ;; Destructively modify keymap
2080 (setcdr keymap (delete-if #'(lambda (item)
2081 (or (null (cdr item))
2082 (and (keymapp (third (cdr item)))
2083 (null (cdr (third (cdr item)))))))
2086 (defun yas-define-menu (mode menu &optional omit-items)
2087 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2089 MENU is a list, its elements can be:
2091 - (yas-item UUID) : Creates an entry the snippet identified with
2092 UUID. The menu entry for a snippet thus identified is
2093 permanent, i.e. it will never move (be reordered) in the menu.
2095 - (yas-separator) : Creates a separator
2097 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2098 SUBMENU has the same form as MENU. NAME is also added to the
2099 list of groups of the snippets defined thereafter.
2101 OMIT-ITEMS is a list of snippet uuid's that will always be
2102 ommited from MODE's menu, even if they're manually loaded.
2104 This function does nothing if `yas-use-menu' is nil.
2107 (let* ((table (yas--table-get-create mode))
2108 (hash (yas--table-uuidhash table)))
2109 (yas--define-menu-1 table
2110 (yas--menu-keymap-get-create mode)
2113 (dolist (uuid omit-items)
2114 (let ((template (or (gethash uuid hash)
2115 (yas--populate-template (puthash uuid
2116 (yas--make-blank-template)
2120 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2122 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2123 (dolist (e (reverse menu))
2124 (cond ((eq (first e) 'yas-item)
2125 (let ((template (or (gethash (second e) uuidhash)
2126 (yas--populate-template (puthash (second e)
2127 (yas--make-blank-template)
2130 :perm-group group-list
2131 :uuid (second e)))))
2132 (define-key menu-keymap (vector (gensym))
2133 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2134 ((eq (first e) 'yas-submenu)
2135 (let ((subkeymap (make-sparse-keymap)))
2136 (define-key menu-keymap (vector (gensym))
2137 `(menu-item ,(second e) ,subkeymap))
2138 (yas--define-menu-1 table
2142 (append group-list (list (second e))))))
2143 ((eq (first e) 'yas-separator)
2144 (define-key menu-keymap (vector (gensym))
2145 '(menu-item "----")))
2147 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2149 (defun yas--define (mode key template &optional name condition group)
2150 "Define a snippet. Expanding KEY into TEMPLATE.
2152 NAME is a description to this template. Also update the menu if
2153 `yas-use-menu' is t. CONDITION is the condition attached to
2154 this snippet. If you attach a condition to a snippet, then it
2155 will only be expanded when the condition evaluated to non-nil."
2156 (yas-define-snippets mode
2157 (list (list key template name condition group))))
2159 (defun yas-hippie-try-expand (first-time?)
2160 "Integrate with hippie expand. Just put this function in
2161 `hippie-expand-try-functions-list'."
2162 (when yas-minor-mode
2163 (if (not first-time?)
2164 (let ((yas-fallback-behavior 'return-nil))
2170 ;;; Apropos condition-cache:
2175 (defvar yas--condition-cache-timestamp nil)
2176 (defmacro yas-define-condition-cache (func doc &rest body)
2177 "Define a function FUNC with doc DOC and body BODY, BODY is
2178 executed at most once every snippet expansion attempt, to check
2179 expansion conditions.
2181 It doesn't make any sense to call FUNC programatically."
2182 `(defun ,func () ,(if (and doc
2185 "\n\nFor use in snippets' conditions. Within each
2186 snippet-expansion routine like `yas-expand', computes actual
2187 value for the first time then always returns a cached value.")
2188 (setq body (cons doc body))
2190 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2191 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2192 (cdr timestamp-and-value)
2193 (let ((new-value (progn
2196 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2199 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2200 (defun yas-expand-from-trigger-key (&optional field)
2201 "Expand a snippet before point.
2203 If no snippet expansion is possible, fall back to the behaviour
2204 defined in `yas-fallback-behavior'.
2206 Optional argument FIELD is for non-interactive use and is an
2207 object satisfying `yas--field-p' to restrict the expansion to."
2209 (setq yas--condition-cache-timestamp (current-time))
2210 (let (templates-and-pos)
2211 (unless (and yas-expand-only-for-last-commands
2212 (not (member last-command yas-expand-only-for-last-commands)))
2213 (setq templates-and-pos (if field
2215 (narrow-to-region (yas--field-start field)
2216 (yas--field-end field))
2218 (yas--current-key))))
2219 (if (and templates-and-pos
2220 (first templates-and-pos))
2221 (yas--expand-or-prompt-for-template (first templates-and-pos)
2222 (second templates-and-pos)
2223 (third templates-and-pos))
2224 (yas--fallback 'trigger-key))))
2226 (defun yas-expand-from-keymap ()
2227 "Directly expand some snippets, searching `yas--direct-keymaps'.
2229 If expansion fails, execute the previous binding for this key"
2231 (setq yas--condition-cache-timestamp (current-time))
2232 (let* ((yas--prefix current-prefix-arg)
2233 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2234 universal-argument-num-events
2236 (templates (mapcan #'(lambda (table)
2237 (yas--fetch table vec))
2238 (yas--get-snippet-tables))))
2240 (yas--expand-or-prompt-for-template templates)
2241 (let ((yas-fallback-behavior 'call-other-command))
2244 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2245 "Expand one of TEMPLATES from START to END.
2247 Prompt the user if TEMPLATES has more than one element, else
2248 expand immediately. Common gateway for
2249 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2250 (let ((yas--current-template (or (and (rest templates) ;; more than one
2251 (yas--prompt-for-template (mapcar #'cdr templates)))
2253 (when yas--current-template
2254 (yas-expand-snippet (yas--template-content yas--current-template)
2257 (yas--template-expand-env yas--current-template)))))
2259 (defun yas--fallback (&optional from-trigger-key-p)
2260 "Fallback after expansion has failed.
2262 Common gateway for `yas-expand-from-trigger-key' and
2263 `yas-expand-from-keymap'."
2264 (cond ((eq yas-fallback-behavior 'return-nil)
2267 ((eq yas-fallback-behavior 'call-other-command)
2268 (let* ((yas-minor-mode nil)
2269 (yas--direct-keymaps nil)
2270 (keys-1 (this-command-keys-vector))
2271 (keys-2 (and yas-trigger-key
2273 (stringp yas-trigger-key)
2274 (read-kbd-macro yas-trigger-key)))
2275 (command-1 (and keys-1 (key-binding keys-1)))
2276 (command-2 (and keys-2 (key-binding keys-2)))
2277 ;; An (ugly) safety: prevents infinite recursion of
2278 ;; yas-expand* calls.
2279 (command (or (and (symbolp command-1)
2280 (not (string-match "yas-expand" (symbol-name command-1)))
2282 (and (symbolp command-2)
2284 (when (and (commandp command)
2285 (not (string-match "yas-expand" (symbol-name command))))
2286 (setq this-command command)
2287 (call-interactively command))))
2288 ((and (listp yas-fallback-behavior)
2289 (cdr yas-fallback-behavior)
2290 (eq 'apply (car yas-fallback-behavior)))
2291 (if (cddr yas-fallback-behavior)
2292 (apply (cadr yas-fallback-behavior)
2293 (cddr yas-fallback-behavior))
2294 (when (commandp (cadr yas-fallback-behavior))
2295 (setq this-command (cadr yas-fallback-behavior))
2296 (call-interactively (cadr yas-fallback-behavior)))))
2298 ;; also return nil if all the other fallbacks have failed
2303 ;;; Utils for snippet development:
2305 (defun yas--all-templates (tables)
2306 "Return all snippet tables applicable for the current buffer.
2308 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2309 `yas-buffer-local-condition'"
2310 (when yas-choose-tables-first
2311 (setq tables (list (yas--prompt-for-table tables))))
2313 (if yas-choose-keys-first
2314 (let ((key (yas--prompt-for-keys
2315 (mapcan #'yas--table-all-keys tables))))
2317 (mapcan #'(lambda (table)
2318 (yas--fetch table key))
2320 (remove-duplicates (mapcan #'yas--table-templates tables)
2323 (defun yas-insert-snippet (&optional no-condition)
2324 "Choose a snippet to expand, pop-up a list of choices according
2325 to `yas--prompt-function'.
2327 With prefix argument NO-CONDITION, bypass filtering of snippets
2330 (setq yas--condition-cache-timestamp (current-time))
2331 (let* ((yas-buffer-local-condition (or (and no-condition
2333 yas-buffer-local-condition))
2334 (templates (yas--all-templates (yas--get-snippet-tables)))
2335 (yas--current-template (and templates
2336 (or (and (rest templates) ;; more than one template for same key
2337 (yas--prompt-for-template templates))
2339 (where (if (region-active-p)
2340 (cons (region-beginning) (region-end))
2341 (cons (point) (point)))))
2342 (if yas--current-template
2343 (yas-expand-snippet (yas--template-content yas--current-template)
2346 (yas--template-expand-env yas--current-template))
2347 (yas--message 3 "No snippets can be inserted here!"))))
2349 (defun yas-visit-snippet-file ()
2350 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2352 Only success if selected snippet was loaded from a file. Put the
2353 visited file in `snippet-mode'."
2355 (let* ((yas-buffer-local-condition 'always)
2356 (templates (yas--all-templates (yas--get-snippet-tables)))
2357 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2358 (template (and templates
2359 (or (yas--prompt-for-template templates
2360 "Choose a snippet template to edit: ")
2364 (yas--visit-snippet-file-1 template)
2365 (message "No snippets tables active!"))))
2367 (defun yas--visit-snippet-file-1 (template)
2368 (let ((file (yas--template-file template)))
2369 (cond ((and file (file-readable-p file))
2370 (find-file-other-window file)
2372 (set (make-local-variable 'yas--editing-template) template))
2374 (message "Original file %s no longer exists!" file))
2376 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2377 (let ((type 'snippet))
2378 (when (listp (yas--template-content template))
2379 (insert (format "# type: command\n"))
2380 (setq type 'command))
2381 (insert (format "# key: %s\n" (yas--template-key template)))
2382 (insert (format "# name: %s\n" (yas--template-name template)))
2383 (when (yas--template-keybinding template)
2384 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2385 (when (yas--template-expand-env template)
2386 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2387 (when (yas--template-condition template)
2388 (insert (format "# condition: %s\n" (yas--template-condition template))))
2390 (insert (if (eq type 'command)
2391 (pp-to-string (yas--template-content template))
2392 (yas--template-content template))))
2394 (set (make-local-variable 'yas--editing-template) template)))))
2396 (defun yas--guess-snippet-directories-1 (table)
2397 "Guesses possible snippet subdirectories for TABLE."
2398 (cons (yas--table-name table)
2399 (mapcan #'(lambda (parent)
2400 (yas--guess-snippet-directories-1
2402 (yas--table-parents table))))
2404 (defun yas--guess-snippet-directories (&optional table)
2405 "Try to guess suitable directories based on the current active
2406 tables (or optional TABLE).
2408 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2409 `yas--table' object and DIRS is a list of all possible directories
2410 where snippets of table might exist."
2411 (let ((main-dir (replace-regexp-in-string
2413 (or (first (or (yas-snippet-dirs)
2414 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2415 (tables (or (and table
2417 (yas--get-snippet-tables))))
2418 ;; HACK! the snippet table created here is actually registered!
2420 (unless (or table (gethash major-mode yas--tables))
2421 (push (yas--table-get-create major-mode)
2424 (mapcar #'(lambda (table)
2426 (mapcar #'(lambda (subdir)
2427 (concat main-dir "/" subdir))
2428 (yas--guess-snippet-directories-1 table))))
2431 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2432 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2433 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2434 (let ((candidate (first (cdr table-and-dirs))))
2435 (unless (file-writable-p (file-name-directory candidate))
2436 (error (yas--format "%s is not writable." candidate)))
2437 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2439 (if (gethash (yas--table-mode (car table-and-dirs))
2443 (or main-table-string
2445 (yas--table-name (car table-and-dirs))))
2447 (make-directory candidate 'also-make-parents)
2448 ;; create the .yas-parents file here...
2451 (defun yas-new-snippet (&optional no-template)
2452 "Pops a new buffer for writing a snippet.
2454 Expands a snippet-writing snippet, unless the optional prefix arg
2455 NO-TEMPLATE is non-nil."
2457 (let ((guessed-directories (yas--guess-snippet-directories)))
2459 (switch-to-buffer "*new snippet*")
2461 (kill-all-local-variables)
2464 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2465 (yas--table-mode (car d)))
2466 guessed-directories))
2467 (unless no-template (yas-expand-snippet "\
2468 # -*- mode: snippet -*-
2470 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2471 # binding: ${4:direct-keybinding}}${5:
2472 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2477 (defun yas--compute-major-mode-and-parents (file)
2478 "Given FILE, find the nearest snippet directory for a given
2479 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2480 representing one or more of the mode's parents.
2482 Note that MODE-SYM need not be the symbol of a real major mode,
2483 neither do the elements of PARENTS."
2484 (let* ((file-dir (and file
2485 (directory-file-name (or (some #'(lambda (special)
2486 (locate-dominating-file file special))
2490 (directory-file-name (file-name-directory file))))))
2491 (parents-file-name (concat file-dir "/.yas-parents"))
2492 (major-mode-name (and file-dir
2493 (file-name-nondirectory file-dir)))
2494 (major-mode-sym (or (and major-mode-name
2495 (intern major-mode-name))))
2496 (parents (when (file-readable-p parents-file-name)
2500 (insert-file-contents parents-file-name)
2501 (buffer-substring-no-properties (point-min)
2503 (when major-mode-sym
2504 (cons major-mode-sym parents))))
2506 (defvar yas--editing-template nil
2507 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'")
2509 (defvar yas--current-template nil
2510 "Holds the current template being expanded into a snippet.")
2512 (defvar yas--guessed-modes nil
2513 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2515 (defun yas-load-snippet-buffer (&optional kill)
2516 "Parse and load current buffer's snippet definition.
2518 With optional prefix argument KILL quit the window and buffer."
2521 ;; We have `yas--editing-template', this buffer's
2522 ;; content comes from a template which is already loaded and
2523 ;; neatly positioned,...
2525 (yas--editing-template
2526 (yas-define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2527 (yas--template-table yas--editing-template)))
2528 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2529 ;; value from `yas--compute-major-mode-and-parents'
2532 (unless yas--guessed-modes
2533 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2534 (let* ((prompt (if (and (featurep 'ido)
2536 'ido-completing-read 'completing-read))
2537 (table (yas--table-get-create
2539 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2540 (if yas--guessed-modes
2541 (first yas--guessed-modes)
2543 (mapcar #'symbol-name yas--guessed-modes)
2548 (if (first yas--guessed-modes)
2549 (symbol-name (first yas--guessed-modes))))))))
2550 (set (make-local-variable 'yas--editing-template)
2551 (yas-define-snippets-1 (yas--parse-template buffer-file-name)
2553 ;; Now, offer to save this iff:
2555 ;; 1) `yas-snippet-dirs' is a list and its first element does not
2556 ;; match this template's file (i.e. this is a library snippet, not
2557 ;; a user snippet) OR
2559 ;; 2) yas--editing-template comes from a file that we cannot write to...
2561 (when (or (not (yas--template-file yas--editing-template))
2562 (not (file-writable-p (yas--template-file yas--editing-template)))
2563 (and (listp yas-snippet-dirs)
2564 (second yas-snippet-dirs)
2565 (not (string-match (expand-file-name (first yas-snippet-dirs))
2566 (yas--template-file yas--editing-template)))))
2568 (when (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? "))
2569 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2571 (yas--make-directory-maybe option))))
2573 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2574 (file-name-nondirectory (yas--template-file yas--editing-template)))
2575 (yas--template-name yas--editing-template))))
2576 (write-file (concat chosen "/"
2577 (read-from-minibuffer (format "File name to create in %s? " chosen)
2578 default-file-name)))
2579 (setf (yas--template-file yas--editing-template) buffer-file-name))))))
2582 (yas--message 3 "Snippet \"%s\" loaded for %s."
2583 (yas--template-name yas--editing-template)
2584 (yas--table-name (yas--template-table yas--editing-template))))
2587 (defun yas-tryout-snippet (&optional debug)
2588 "Test current buffers's snippet template in other buffer."
2590 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2591 (parsed (yas--parse-template))
2592 (test-mode (or (and (car major-mode-and-parent)
2593 (fboundp (car major-mode-and-parent))
2594 (car major-mode-and-parent))
2595 (first yas--guessed-modes)
2596 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2597 (yas--current-template
2600 (yas--populate-template (yas--make-blank-template)
2601 :table nil ;; no tables for ephemeral snippets
2603 :content (second parsed)
2604 :name (third parsed)
2605 :expand-env (sixth parsed)))))
2606 (cond (yas--current-template
2607 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2608 (kill-buffer (get-buffer-create buffer-name))
2609 (switch-to-buffer (get-buffer-create buffer-name))
2610 (setq buffer-undo-list nil)
2611 (condition-case nil (funcall test-mode) (error nil))
2612 (setq buffer-read-only nil)
2613 (yas-expand-snippet (yas--template-content yas--current-template)
2616 (yas--template-expand-env yas--current-template))
2618 (require 'yasnippet-debug nil t))
2619 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2621 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2623 (defun yas--template-fine-group (template)
2624 (car (last (or (yas--template-group template)
2625 (yas--template-perm-group template)))))
2627 (defun yas-describe-tables (&optional choose)
2628 "Display snippets for each table."
2630 (let* ((by-name-hash (and choose
2631 (y-or-n-p "Show by namehash? ")))
2632 (buffer (get-buffer-create "*YASnippet tables*"))
2633 (active-tables (yas--get-snippet-tables))
2634 (remain-tables (let ((all))
2635 (maphash #'(lambda (k v)
2636 (unless (find v active-tables)
2640 (table-lists (list active-tables remain-tables))
2641 (original-buffer (current-buffer))
2643 (yas--condition-cache-timestamp (current-time)))
2644 (with-current-buffer buffer
2645 (setq buffer-read-only nil)
2647 (cond ((not by-name-hash)
2648 (insert "YASnippet tables: \n")
2649 (while (and table-lists
2651 (dolist (table (car table-lists))
2652 (yas--describe-pretty-table table original-buffer))
2653 (setq table-lists (cdr table-lists))
2655 (yas--create-snippet-xrefs)
2656 (display-buffer buffer)
2657 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2658 (yas--create-snippet-xrefs)
2662 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2663 (dolist (table (append active-tables remain-tables))
2664 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2666 (maphash #'(lambda (k v)
2668 (yas--table-hash table))
2670 (insert (format " key %s maps snippets: %s\n" key
2672 (maphash #'(lambda (k v)
2674 (gethash key (yas--table-hash table)))
2677 (setq buffer-read-only t))
2678 (display-buffer buffer)))
2680 (defun yas--describe-pretty-table (table &optional original-buffer)
2681 (insert (format "\nSnippet table `%s'"
2682 (yas--table-name table)))
2683 (if (yas--table-parents table)
2684 (insert (format " parents: %s\n"
2685 (mapcar #'yas--table-name
2686 (yas--table-parents table))))
2688 (insert (make-string 100 ?-) "\n")
2689 (insert "group state name key binding\n")
2690 (let ((groups-hash (make-hash-table :test #'equal)))
2691 (maphash #'(lambda (k v)
2692 (let ((group (or (yas--template-fine-group v)
2694 (when (yas--template-name v)
2696 (cons v (gethash group groups-hash))
2698 (yas--table-uuidhash table))
2700 #'(lambda (group templates)
2701 (setq group (truncate-string-to-width group 25 0 ? "..."))
2702 (insert (make-string 100 ?-) "\n")
2703 (dolist (p templates)
2704 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2708 (setq group (make-string (length group) ? ))))
2709 (condition-string (let ((condition (yas--template-condition p)))
2712 (with-current-buffer original-buffer
2713 (if (yas--eval-condition condition)
2718 (insert condition-string " ")
2720 (if (string-match "\\.\\.\\.$" name)
2724 (insert (truncate-string-to-width (or (yas--template-key p) "")
2726 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2733 ;;; User convenience functions, for using in snippet definitions
2735 (defvar yas-modified-p nil
2736 "Non-nil if field has been modified by user or transformation.")
2738 (defvar yas-moving-away-p nil
2739 "Non-nil if user is about to exit field.")
2741 (defvar yas-text nil
2742 "Contains current field text.")
2744 (defun yas-substr (str pattern &optional subexp)
2745 "Search PATTERN in STR and return SUBEXPth match.
2747 If found, the content of subexp group SUBEXP (default 0) is
2748 returned, or else the original STR will be returned."
2749 (let ((grp (or subexp 0)))
2751 (if (string-match pattern str)
2752 (match-string-no-properties grp str)
2755 (defun yas-choose-avalue (&rest possibilities)
2756 "Prompt for a string in POSSIBILITIES and return it.
2758 The last element of POSSIBILITIES may be a list of strings."
2759 (unless (or yas-moving-away-p
2761 (setq possibilities (nreverse possibilities))
2762 (setq possibilities (if (listp (car possibilities))
2763 (append (reverse (car possibilities)) (rest possibilities))
2765 (some #'(lambda (fn)
2766 (funcall fn "Choose: " possibilities))
2767 yas-prompt-functions)))
2769 (defun yas-key-to-value (alist)
2770 "Prompt for a string in the list POSSIBILITIES and return it."
2771 (unless (or yas-moving-away-p
2773 (let ((key (read-key-sequence "")))
2775 (or (cdr (find key alist :key #'car :test #'string=))
2778 (defun yas-throw (text)
2779 "Throw a yas--exception with TEXT as the reason."
2780 (throw 'yas--exception (cons 'yas--exception text)))
2782 (defun yas-verify-value (possibilities)
2783 "Verify that the current field value is in POSSIBILITIES
2785 Otherwise throw exception."
2786 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2787 (yas-throw (yas--format "Field only allows %s" possibilities))))
2789 (defun yas-field-value (number)
2790 "Get the string for field with NUMBER.
2792 Use this in primary and mirror transformations to tget."
2793 (let* ((snippet (car (yas--snippets-at-point)))
2795 (yas--snippet-find-field snippet number))))
2797 (yas--field-text-for-display field))))
2800 "Return `yas-text' if that exists and is non-empty, else nil."
2802 (not (string= "" yas-text)))
2805 (defun yas-selected-text ()
2806 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2807 (if (and yas-selected-text
2808 (not (string= "" yas-selected-text)))
2811 (defun yas--get-field-once (number &optional transform-fn)
2812 (unless yas-modified-p
2814 (funcall transform-fn (yas-field-value number))
2815 (yas-field-value number))))
2817 (defun yas-default-from-field (number)
2818 (unless yas-modified-p
2819 (yas-field-value number)))
2821 (defun yas-inside-string ()
2822 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2824 (defun yas-unimplemented (&optional missing-feature)
2825 (if yas--current-template
2826 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2829 (yas--visit-snippet-file-1 yas--current-template))
2830 (message "No implementation. Missing %s" (or missing-feature "something"))))
2833 ;;; Snippet expansion and field management
2835 (defvar yas--active-field-overlay nil
2836 "Overlays the currently active field.")
2838 (defvar yas--field-protection-overlays nil
2839 "Two overlays protect the current active field ")
2841 (defconst yas--prefix nil
2842 "A prefix argument for expansion direct from keybindings")
2844 (defvar yas-selected-text nil
2845 "The selected region deleted on the last snippet expansion.")
2847 (defvar yas--start-column nil
2848 "The column where the snippet expansion started.")
2850 (make-variable-buffer-local 'yas--active-field-overlay)
2851 (make-variable-buffer-local 'yas--field-protection-overlays)
2852 (put 'yas--active-field-overlay 'permanent-local t)
2853 (put 'yas--field-protection-overlays 'permanent-local t)
2855 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2861 (id (yas--snippet-next-id) :read-only t)
2862 (control-overlay nil)
2864 ;; stacked expansion: the `previous-active-field' slot saves the
2865 ;; active field where the child expansion took place
2866 previous-active-field
2869 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2879 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2886 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2890 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2891 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2893 If there is no transform for ht field, return nil.
2895 If there is a transform but it returns nil, return the empty
2896 string iff EMPTY-ON-NIL-P is true."
2897 (let* ((yas-text (yas--field-text-for-display field))
2899 (yas-modified-p (yas--field-modified-p field))
2900 (yas-moving-away-p nil)
2901 (transform (if (yas--mirror-p field-or-mirror)
2902 (yas--mirror-transform field-or-mirror)
2903 (yas--field-transform field-or-mirror)))
2904 (start-point (if (yas--mirror-p field-or-mirror)
2905 (yas--mirror-start field-or-mirror)
2906 (yas--field-start field-or-mirror)))
2907 (transformed (and transform
2909 (goto-char start-point)
2910 (let ((ret (yas--eval-lisp transform)))
2911 (or ret (and empty-on-nil-p "")))))))
2914 (defsubst yas--replace-all (from to &optional text)
2915 "Replace all occurance from FROM to TO.
2917 With optional string TEXT do it in that string."
2919 (replace-regexp-in-string (regexp-quote from) to text t t)
2920 (goto-char (point-min))
2921 (while (search-forward from nil t)
2922 (replace-match to t t text))))
2924 (defun yas--snippet-find-field (snippet number)
2925 (find-if #'(lambda (field)
2926 (eq number (yas--field-number field)))
2927 (yas--snippet-fields snippet)))
2929 (defun yas--snippet-sort-fields (snippet)
2930 "Sort the fields of SNIPPET in navigation order."
2931 (setf (yas--snippet-fields snippet)
2932 (sort (yas--snippet-fields snippet)
2933 #'yas--snippet-field-compare)))
2935 (defun yas--snippet-field-compare (field1 field2)
2936 "Compare two fields. The field with a number is sorted first.
2937 If they both have a number, compare through the number. If neither
2938 have, compare through the field's start point"
2939 (let ((n1 (yas--field-number field1))
2940 (n2 (yas--field-number field2)))
2943 (or (zerop n2) (and (not (zerop n1))
2948 (< (yas--field-start field1)
2949 (yas--field-start field2))))))
2951 (defun yas--field-probably-deleted-p (snippet field)
2952 "Guess if SNIPPET's FIELD should be skipped."
2954 ;; field must be zero lentgh
2956 (zerop (- (yas--field-start field) (yas--field-end field)))
2959 ;; 1) is a nested field and it's been modified
2961 (and (yas--field-parent-field field)
2962 (yas--field-modified-p field))
2963 ;; 2) ends just before the snippet end
2965 (and (eq field (car (last (yas--snippet-fields snippet))))
2966 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2967 ;; the field numbered 0, just before the exit marker, should
2970 (not (zerop (yas--field-number field)))))
2972 (defun yas--snippets-at-point (&optional all-snippets)
2973 "Return a sorted list of snippets at point, most recently
2976 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2977 (overlay-get ov 'yas--snippet))
2979 (overlays-in (point-min) (point-max))
2980 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2982 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2984 (defun yas-next-field-or-maybe-expand ()
2985 "Try to expand a snippet at a key before point, otherwise
2986 delegate to `yas-next-field'."
2988 (if yas-triggers-in-field
2989 (let ((yas-fallback-behavior 'return-nil)
2990 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2992 (unless (yas-expand-from-trigger-key active-field)
2996 (defun yas-next-field (&optional arg)
2997 "Navigate to next field. If there's none, exit the snippet."
3001 (snippet (first (yas--snippets-at-point)))
3002 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3003 (live-fields (remove-if #'(lambda (field)
3004 (and (not (eq field active-field))
3005 (yas--field-probably-deleted-p snippet field)))
3006 (yas--snippet-fields snippet)))
3007 (active-field-pos (position active-field live-fields))
3008 (target-pos (and active-field-pos (+ arg active-field-pos)))
3009 (target-field (and target-pos (nth target-pos live-fields))))
3010 ;; First check if we're moving out of a field with a transform
3012 (when (and active-field
3013 (yas--field-transform active-field))
3014 (let* ((yas-moving-away-p t)
3015 (yas-text (yas--field-text-for-display active-field))
3017 (yas-modified-p (yas--field-modified-p active-field)))
3018 ;; primary field transform: exit call to field-transform
3019 (yas--eval-lisp (yas--field-transform active-field))))
3020 ;; Now actually move...
3021 (cond ((and target-pos (>= target-pos (length live-fields)))
3022 (yas-exit-snippet snippet))
3024 (yas--move-to-field snippet target-field))
3028 (defun yas--place-overlays (snippet field)
3029 "Correctly place overlays for SNIPPET's FIELD"
3030 (yas--make-move-field-protection-overlays snippet field)
3031 (yas--make-move-active-field-overlay snippet field))
3033 (defun yas--move-to-field (snippet field)
3034 "Update SNIPPET to move to field FIELD.
3036 Also create some protection overlays"
3037 (goto-char (yas--field-start field))
3038 (yas--place-overlays snippet field)
3039 (overlay-put yas--active-field-overlay 'yas--field field)
3040 (let ((number (yas--field-number field)))
3041 ;; check for the special ${0: ...} field
3042 (if (and number (zerop number))
3044 (set-mark (yas--field-end field))
3045 (setf (yas--snippet-force-exit snippet)
3046 (or (yas--field-transform field)
3048 ;; make this field active
3049 (setf (yas--snippet-active-field snippet) field)
3050 ;; primary field transform: first call to snippet transform
3051 (unless (yas--field-modified-p field)
3052 (if (yas--field-update-display field snippet)
3053 (yas--update-mirrors snippet)
3054 (setf (yas--field-modified-p field) nil))))))
3056 (defun yas-prev-field ()
3057 "Navigate to prev field. If there's none, exit the snippet."
3059 (yas-next-field -1))
3061 (defun yas-abort-snippet (&optional snippet)
3063 (let ((snippet (or snippet
3064 (car (yas--snippets-at-point)))))
3066 (setf (yas--snippet-force-exit snippet) t))))
3068 (defun yas-exit-snippet (snippet)
3069 "Goto exit-marker of SNIPPET."
3070 (interactive (list (first (yas--snippets-at-point))))
3072 (setf (yas--snippet-force-exit snippet) t)
3073 (goto-char (if (yas--snippet-exit snippet)
3074 (yas--exit-marker (yas--snippet-exit snippet))
3075 (overlay-end (yas--snippet-control-overlay snippet))))))
3077 (defun yas-exit-all-snippets ()
3078 "Exit all snippets."
3080 (mapc #'(lambda (snippet)
3081 (yas-exit-snippet snippet)
3082 (yas--check-commit-snippet))
3083 (yas--snippets-at-point 'all-snippets)))
3086 ;;; Some low level snippet-routines:
3088 (defmacro yas--inhibit-overlay-hooks (&rest body)
3089 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3090 (declare (indent 0))
3091 `(let ((yas--inhibit-overlay-hooks t))
3094 (defvar yas-snippet-beg nil "Beginning position of the last snippet commited.")
3095 (defvar yas-snippet-end nil "End position of the last snippet commited.")
3097 (defun yas--commit-snippet (snippet)
3098 "Commit SNIPPET, but leave point as it is. This renders the
3099 snippet as ordinary text."
3101 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3103 ;; Save the end of the moribund snippet in case we need to revive it
3104 ;; its original expansion.
3106 (when (and control-overlay
3107 (overlay-buffer control-overlay))
3108 (setq yas-snippet-beg (overlay-start control-overlay))
3109 (setq yas-snippet-end (overlay-end control-overlay))
3110 (delete-overlay control-overlay))
3112 (yas--inhibit-overlay-hooks
3113 (when yas--active-field-overlay
3114 (delete-overlay yas--active-field-overlay))
3115 (when yas--field-protection-overlays
3116 (mapc #'delete-overlay yas--field-protection-overlays)))
3118 ;; stacked expansion: if the original expansion took place from a
3119 ;; field, make sure we advance it here at least to
3120 ;; `yas-snippet-end'...
3122 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3123 (when (and yas-snippet-end previous-field)
3124 (yas--advance-end-maybe previous-field yas-snippet-end)))
3126 ;; Convert all markers to points,
3128 (yas--markers-to-points snippet)
3130 ;; Take care of snippet revival
3132 (if yas-snippet-revival
3133 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3135 ;; Dismember the snippet... this is useful if we get called
3136 ;; again from `yas--take-care-of-redo'....
3137 (setf (yas--snippet-fields snippet) nil)))
3139 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3141 (defun yas--safely-run-hooks (hook-var)
3142 (condition-case error
3143 (run-hooks hook-var)
3145 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3148 (defun yas--check-commit-snippet ()
3149 "Checks if point exited the currently active field of the
3150 snippet, if so cleans up the whole snippet up."
3151 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3152 (snippets-left snippets)
3153 (snippet-exit-transform))
3154 (dolist (snippet snippets)
3155 (let ((active-field (yas--snippet-active-field snippet)))
3156 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3157 (cond ((or snippet-exit-transform
3158 (not (and active-field (yas--field-contains-point-p active-field))))
3159 (setq snippets-left (delete snippet snippets-left))
3160 (setf (yas--snippet-force-exit snippet) nil)
3161 (yas--commit-snippet snippet))
3163 (or (not yas--active-field-overlay)
3164 (not (overlay-buffer yas--active-field-overlay))))
3166 ;; stacked expansion: this case is mainly for recent
3167 ;; snippet exits that place us back int the field of
3171 (yas--move-to-field snippet active-field)
3172 (yas--update-mirrors snippet)))
3175 (unless (or (null snippets) snippets-left)
3176 (if snippet-exit-transform
3177 (yas--eval-lisp-no-saves snippet-exit-transform))
3178 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3180 ;; Apropos markers-to-points:
3182 ;; This was found useful for performance reasons, so that an
3183 ;; excessive number of live markers aren't kept around in the
3184 ;; `buffer-undo-list'. However, in `markers-to-points', the
3185 ;; set-to-nil markers can't simply be discarded and replaced with
3186 ;; fresh ones in `points-to-markers'. The original marker that was
3187 ;; just set to nil has to be reused.
3189 ;; This shouldn't bring horrible problems with undo/redo, but it
3192 (defun yas--markers-to-points (snippet)
3193 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3194 where POINT is the original position of the marker and MARKER is
3195 the original marker object with the position set to nil."
3196 (dolist (field (yas--snippet-fields snippet))
3197 (let ((start (marker-position (yas--field-start field)))
3198 (end (marker-position (yas--field-end field))))
3199 (set-marker (yas--field-start field) nil)
3200 (set-marker (yas--field-end field) nil)
3201 (setf (yas--field-start field) (cons start (yas--field-start field)))
3202 (setf (yas--field-end field) (cons end (yas--field-end field))))
3203 (dolist (mirror (yas--field-mirrors field))
3204 (let ((start (marker-position (yas--mirror-start mirror)))
3205 (end (marker-position (yas--mirror-end mirror))))
3206 (set-marker (yas--mirror-start mirror) nil)
3207 (set-marker (yas--mirror-end mirror) nil)
3208 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3209 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3210 (let ((snippet-exit (yas--snippet-exit snippet)))
3212 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3213 (set-marker (yas--exit-marker snippet-exit) nil)
3214 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3216 (defun yas--points-to-markers (snippet)
3217 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3218 is done by setting MARKER to POINT with `set-marker'."
3219 (dolist (field (yas--snippet-fields snippet))
3220 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3221 (car (yas--field-start field))))
3222 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3223 (car (yas--field-end field))))
3224 (dolist (mirror (yas--field-mirrors field))
3225 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3226 (car (yas--mirror-start mirror))))
3227 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3228 (car (yas--mirror-end mirror))))))
3229 (let ((snippet-exit (yas--snippet-exit snippet)))
3231 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3232 (car (yas--exit-marker snippet-exit)))))))
3234 (defun yas--field-contains-point-p (field &optional point)
3235 (let ((point (or point
3237 (and (>= point (yas--field-start field))
3238 (<= point (yas--field-end field)))))
3240 (defun yas--field-text-for-display (field)
3241 "Return the propertized display text for field FIELD. "
3242 (buffer-substring (yas--field-start field) (yas--field-end field)))
3244 (defun yas--undo-in-progress ()
3245 "True if some kind of undo is in progress"
3246 (or undo-in-progress
3247 (eq this-command 'undo)
3248 (eq this-command 'redo)))
3250 (defun yas--make-control-overlay (snippet start end)
3251 "Creates the control overlay that surrounds the snippet and
3253 (let ((overlay (make-overlay start
3258 (overlay-put overlay 'keymap yas-keymap)
3259 (overlay-put overlay 'priority 100)
3260 (overlay-put overlay 'yas--snippet snippet)
3263 (defun yas-skip-and-clear-or-delete-char (&optional field)
3264 "Clears unmodified field if at field start, skips to next tab.
3266 Otherwise deletes a character normally by calling `delete-char'."
3268 (let ((field (or field
3269 (and yas--active-field-overlay
3270 (overlay-buffer yas--active-field-overlay)
3271 (overlay-get yas--active-field-overlay 'yas--field)))))
3273 (not (yas--field-modified-p field))
3274 (eq (point) (marker-position (yas--field-start field))))
3275 (yas--skip-and-clear field)
3278 (call-interactively 'delete-char)))))
3280 (defun yas--skip-and-clear (field)
3281 "Deletes the region of FIELD and sets it modified state to t"
3282 ;; Just before skipping-and-clearing the field, mark its children
3283 ;; fields as modified, too. If the childen have mirrors-in-fields
3284 ;; this prevents them from updating erroneously (we're skipping and
3287 (yas--mark-this-and-children-modified field)
3288 (delete-region (yas--field-start field) (yas--field-end field)))
3290 (defun yas--mark-this-and-children-modified (field)
3291 (setf (yas--field-modified-p field) t)
3292 (let ((fom (yas--field-next field)))
3294 (yas--fom-parent-field fom))
3295 (when (and (eq (yas--fom-parent-field fom) field)
3297 (yas--mark-this-and-children-modified fom))
3298 (setq fom (yas--fom-next fom)))))
3300 (defun yas--make-move-active-field-overlay (snippet field)
3301 "Place the active field overlay in SNIPPET's FIELD.
3303 Move the overlay, or create it if it does not exit."
3304 (if (and yas--active-field-overlay
3305 (overlay-buffer yas--active-field-overlay))
3306 (move-overlay yas--active-field-overlay
3307 (yas--field-start field)
3308 (yas--field-end field))
3309 (setq yas--active-field-overlay
3310 (make-overlay (yas--field-start field)
3311 (yas--field-end field)
3313 (overlay-put yas--active-field-overlay 'priority 100)
3314 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3315 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3316 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3317 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3318 '(yas--on-field-overlay-modification))
3319 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3320 '(yas--on-field-overlay-modification))))
3322 (defvar yas--inhibit-overlay-hooks nil
3323 "Bind this temporarity to non-nil to prevent running `yas--on-*-modification'.")
3325 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3326 "Clears the field and updates mirrors, conditionally.
3328 Only clears the field if it hasn't been modified and it point it
3329 at field start. This hook doesn't do anything if an undo is in
3331 (unless (or yas--inhibit-overlay-hooks
3332 (yas--undo-in-progress))
3333 (let* ((field (overlay-get overlay 'yas--field))
3334 (number (and field (yas--field-number field)))
3335 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3337 (yas--advance-end-maybe field (overlay-end overlay))
3339 (yas--field-update-display field snippet))
3340 (yas--update-mirrors snippet))
3342 (when (and (not after?)
3343 (not (yas--field-modified-p field))
3344 (eq (point) (if (markerp (yas--field-start field))
3345 (marker-position (yas--field-start field))
3346 (yas--field-start field))))
3347 (yas--skip-and-clear field))
3348 (setf (yas--field-modified-p field) t))))))
3350 ;;; Apropos protection overlays:
3352 ;; These exist for nasty users who will try to delete parts of the
3353 ;; snippet outside the active field. Actual protection happens in
3354 ;; `yas--on-protection-overlay-modification'.
3356 ;; Currently this signals an error which inhibits the command. For
3357 ;; commands that move point (like `kill-line'), point is restored in
3358 ;; the `yas--post-command-handler' using a global
3359 ;; `yas--protection-violation' variable.
3361 ;; Alternatively, I've experimented with an implementation that
3362 ;; commits the snippet before actually calling `this-command'
3363 ;; interactively, and then signals an eror, which is ignored. but
3364 ;; blocks all other million modification hooks. This presented some
3365 ;; problems with stacked expansion.
3367 (defun yas--make-move-field-protection-overlays (snippet field)
3368 "Place protection overlays surrounding SNIPPET's FIELD.
3370 Move the overlays, or create them if they do not exit."
3371 (let ((start (yas--field-start field))
3372 (end (yas--field-end field)))
3373 ;; First check if the (1+ end) is contained in the buffer,
3374 ;; otherwise we'll have to do a bit of cheating and silently
3375 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3376 ;; when using stacked expansion
3378 (when (< (buffer-size) end)
3380 (yas--inhibit-overlay-hooks
3381 (goto-char (point-max))
3383 ;; go on to normal overlay creation/moving
3385 (cond ((and yas--field-protection-overlays
3386 (every #'overlay-buffer yas--field-protection-overlays))
3387 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3388 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3390 (setq yas--field-protection-overlays
3391 (list (make-overlay (1- start) start nil t nil)
3392 (make-overlay end (1+ end) nil t nil)))
3393 (dolist (ov yas--field-protection-overlays)
3394 (overlay-put ov 'face 'yas--field-debug-face)
3395 (overlay-put ov 'yas--snippet snippet)
3396 ;; (overlay-put ov 'evaporate t)
3397 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3399 (defvar yas--protection-violation nil
3400 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3402 Functions in the `post-command-hook', for example
3403 `yas--post-command-handler' can check it and reset its value to
3404 nil. The variables value is the point where the violation
3407 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3408 "Signals a snippet violation, then issues error.
3410 The error should be ignored in `debug-ignored-errors'"
3411 (unless yas--inhibit-overlay-hooks
3412 (cond ((not (or after?
3413 (yas--undo-in-progress)))
3414 (setq yas--protection-violation (point))
3415 (error "Exit the snippet first!")))))
3417 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3420 ;; Snippet expansion and "stacked" expansion:
3422 ;; Stacked expansion is when you try to expand a snippet when already
3423 ;; inside a snippet expansion.
3425 ;; The parent snippet does not run its fields modification hooks
3426 ;; (`yas--on-field-overlay-modification' and
3427 ;; `yas--on-protection-overlay-modification') while the child snippet
3428 ;; is active. This means, among other things, that the mirrors of the
3429 ;; parent snippet are not updated, this only happening when one exits
3430 ;; the child snippet.
3432 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3433 ;; bits of code in `yas-expand-snippet' and
3434 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3437 ;; This was thought to be safer in in an undo/redo perpective, but
3438 ;; maybe the correct implementation is to make the globals
3439 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3440 ;; snippet-local and be active even while the child snippet is
3441 ;; running. This would mean a lot of overlay modification hooks
3442 ;; running, but if managed correctly (including overlay priorities)
3443 ;; they should account for all situations...
3445 (defun yas-expand-snippet (content &optional start end expand-env)
3446 "Expand snippet CONTENT at current point.
3448 Text between START and END will be deleted before inserting
3449 template. EXPAND-ENV is are let-style variable to value bindings
3450 considered when expanding the snippet."
3451 (run-hooks 'yas-before-expand-snippet-hook)
3454 (let* ((yas-selected-text (or yas-selected-text
3455 (and (region-active-p)
3456 (buffer-substring-no-properties (region-beginning)
3459 (and (region-active-p)
3463 (and (region-active-p)
3466 (to-delete (and start
3468 (buffer-substring-no-properties start end)))
3471 (setq yas--indent-original-column (current-column))
3472 ;; Delete the region to delete, this *does* get undo-recorded.
3474 (when (and to-delete
3476 (delete-region start end))
3478 (cond ((listp content)
3479 ;; x) This is a snippet-command
3481 (yas--eval-lisp-no-saves content))
3483 ;; x) This is a snippet-snippet :-)
3485 ;; Narrow the region down to the content, shoosh the
3486 ;; `buffer-undo-list', and create the snippet, the new
3487 ;; snippet updates its mirrors once, so we are left with
3488 ;; some plain text. The undo action for deleting this
3489 ;; plain text will get recorded at the end.
3491 ;; stacked expansion: also shoosh the overlay modification hooks
3493 (narrow-to-region start start)
3494 (let ((buffer-undo-list t))
3495 ;; snippet creation might evaluate users elisp, which
3496 ;; might generate errors, so we have to be ready to catch
3497 ;; them mostly to make the undo information
3499 (setq yas--start-column (save-restriction (widen) (current-column)))
3500 (yas--inhibit-overlay-hooks
3503 (eval `(let* ,expand-env
3505 (yas--snippet-create (point-min) (point-max))))
3507 (yas--snippet-create (point-min) (point-max)))))))
3509 ;; stacked-expansion: This checks for stacked expansion, save the
3510 ;; `yas--previous-active-field' and advance its boudary.
3512 (let ((existing-field (and yas--active-field-overlay
3513 (overlay-buffer yas--active-field-overlay)
3514 (overlay-get yas--active-field-overlay 'yas--field))))
3515 (when existing-field
3516 (setf (yas--snippet-previous-active-field snippet) existing-field)
3517 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3519 ;; Exit the snippet immediately if no fields
3521 (unless (yas--snippet-fields snippet)
3522 (yas-exit-snippet snippet))
3524 ;; Push two undo actions: the deletion of the inserted contents of
3525 ;; the new snippet (without the "key") followed by an apply of
3526 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3528 ;; A small exception, if `yas-also-auto-indent-first-line'
3529 ;; is t and `yas--indent' decides to indent the line to a
3530 ;; point before the actual expansion point, undo would be
3531 ;; messed up. We call the early point "newstart"". case,
3532 ;; and attempt to fix undo.
3534 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3535 (end (overlay-end (yas--snippet-control-overlay snippet))))
3536 (when (< newstart start)
3537 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3538 (push (cons newstart end) buffer-undo-list)
3539 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3541 ;; Now, schedule a move to the first field
3543 (let ((first-field (car (yas--snippet-fields snippet))))
3545 (sit-for 0) ;; fix issue 125
3546 (yas--move-to-field snippet first-field)))
3547 (yas--message 3 "snippet expanded.")
3550 (defun yas--take-care-of-redo (beg end snippet)
3551 "Commits SNIPPET, which in turn pushes an undo action for
3554 Meant to exit in the `buffer-undo-list'."
3555 ;; slightly optimize: this action is only needed for snippets with
3556 ;; at least one field
3557 (when (yas--snippet-fields snippet)
3558 (yas--commit-snippet snippet)))
3560 (defun yas--snippet-revive (beg end snippet)
3561 "Revives the SNIPPET and creates a control overlay from BEG to
3564 BEG and END are, we hope, the original snippets boudaries. All
3565 the markers/points exiting existing inside SNIPPET should point
3566 to their correct locations *at the time the snippet is revived*.
3568 After revival, push the `yas--take-care-of-redo' in the
3570 ;; Reconvert all the points to markers
3572 (yas--points-to-markers snippet)
3573 ;; When at least one editable field existed in the zombie snippet,
3574 ;; try to revive the whole thing...
3576 (let ((target-field (or (yas--snippet-active-field snippet)
3577 (car (yas--snippet-fields snippet)))))
3579 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3580 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3582 (yas--move-to-field snippet target-field)
3584 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3585 buffer-undo-list))))
3587 (defun yas--snippet-create (begin end)
3588 "Creates a snippet from an template inserted between BEGIN and END.
3590 Returns the newly created snippet."
3591 (let ((snippet (yas--make-snippet)))
3593 (yas--snippet-parse-create snippet)
3595 ;; Sort and link each field
3596 (yas--snippet-sort-fields snippet)
3598 ;; Create keymap overlay for snippet
3599 (setf (yas--snippet-control-overlay snippet)
3600 (yas--make-control-overlay snippet (point-min) (point-max)))
3603 (goto-char (point-max))
3608 ;;; Apropos adjacencies and "fom's":
3610 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3611 ;; recently expanded snippet, we might actually have many fields,
3612 ;; mirrors (and the snippet exit) in the very same position in the
3613 ;; buffer. Therefore we need to single-link the
3614 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3615 ;; according to their original positions in the buffer.
3617 ;; Then we have operation `yas--advance-end-maybe' and
3618 ;; `yas--advance-start-maybe', which conditionally push the starts and
3619 ;; ends of these foms down the chain.
3621 ;; This allows for like the printf with the magic ",":
3623 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3624 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3626 (defun yas--fom-start (fom)
3627 (cond ((yas--field-p fom)
3628 (yas--field-start fom))
3629 ((yas--mirror-p fom)
3630 (yas--mirror-start fom))
3632 (yas--exit-marker fom))))
3634 (defun yas--fom-end (fom)
3635 (cond ((yas--field-p fom)
3636 (yas--field-end fom))
3637 ((yas--mirror-p fom)
3638 (yas--mirror-end fom))
3640 (yas--exit-marker fom))))
3642 (defun yas--fom-next (fom)
3643 (cond ((yas--field-p fom)
3644 (yas--field-next fom))
3645 ((yas--mirror-p fom)
3646 (yas--mirror-next fom))
3648 (yas--exit-next fom))))
3650 (defun yas--fom-parent-field (fom)
3651 (cond ((yas--field-p fom)
3652 (yas--field-parent-field fom))
3653 ((yas--mirror-p fom)
3654 (yas--mirror-parent-field fom))
3658 (defun yas--calculate-adjacencies (snippet)
3659 "Calculate adjacencies for fields or mirrors of SNIPPET.
3661 This is according to their relative positions in the buffer, and
3662 has to be called before the $-constructs are deleted."
3663 (flet ((yas--fom-set-next-fom (fom nextfom)
3664 (cond ((yas--field-p fom)
3665 (setf (yas--field-next fom) nextfom))
3666 ((yas--mirror-p fom)
3667 (setf (yas--mirror-next fom) nextfom))
3669 (setf (yas--exit-next fom) nextfom))))
3670 (yas--compare-fom-begs (fom1 fom2)
3671 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3672 (yas--mirror-p fom2)
3673 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3674 (yas--link-foms (fom1 fom2)
3675 (yas--fom-set-next-fom fom1 fom2)))
3676 ;; make some yas--field, yas--mirror and yas--exit soup
3678 (when (yas--snippet-exit snippet)
3679 (push (yas--snippet-exit snippet) soup))
3680 (dolist (field (yas--snippet-fields snippet))
3682 (dolist (mirror (yas--field-mirrors field))
3683 (push mirror soup)))
3686 #'yas--compare-fom-begs))
3688 (reduce #'yas--link-foms soup)))))
3690 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3691 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3693 Use the tighest containing field if more than one field contains
3694 the mirror. Intended to be called *before* the dollar-regions are
3696 (let ((min (point-min))
3698 (dolist (field (yas--snippet-fields snippet))
3699 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3700 (<= (yas--mirror-end mirror) (yas--field-end field))
3701 (< min (yas--field-start field))
3702 (< (yas--field-end field) max))
3703 (setq min (yas--field-start field)
3704 max (yas--field-end field))
3705 (setf (yas--mirror-parent-field mirror) field)))))
3707 (defun yas--advance-end-maybe (fom newend)
3708 "Maybe advance FOM's end to NEWEND if it needs it.
3712 * call `yas--advance-start-maybe' on FOM's next fom.
3714 * in case FOM is field call `yas--advance-end-maybe' on its parent
3717 Also, if FOM is an exit-marker, always call
3718 `yas--advance-start-maybe' on its next fom. This is beacuse
3719 exit-marker have identical start and end markers.
3722 (cond ((and fom (< (yas--fom-end fom) newend))
3723 (set-marker (yas--fom-end fom) newend)
3724 (yas--advance-start-maybe (yas--fom-next fom) newend)
3725 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3727 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3729 (defun yas--advance-start-maybe (fom newstart)
3730 "Maybe advance FOM's start to NEWSTART if it needs it.
3732 If it does, also call `yas--advance-end-maybe' on FOM."
3733 (when (and fom (< (yas--fom-start fom) newstart))
3734 (set-marker (yas--fom-start fom) newstart)
3735 (yas--advance-end-maybe fom newstart)))
3737 (defun yas--advance-end-of-parents-maybe (field newend)
3738 "Like `yas--advance-end-maybe' but for parent fields.
3740 Only works for fields and doesn't care about the start of the
3741 next FOM. Works its way up recursively for parents of parents."
3743 (< (yas--field-end field) newend))
3744 (set-marker (yas--field-end field) newend)
3745 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3747 (defvar yas--dollar-regions nil
3748 "When expanding the snippet the \"parse-create\" functions add
3749 cons cells to this var")
3751 (defvar yas--backquote-markers-and-strings nil
3752 "List of (MARKER . STRING) marking where the the values
3753 from backquoted lisp expressions should be inserted at the end of
3756 (defun yas--snippet-parse-create (snippet)
3757 "Parse a recently inserted snippet template, creating all
3758 necessary fields, mirrors and exit points.
3760 Meant to be called in a narrowed buffer, does various passes"
3761 (let ((parse-start (point)))
3762 ;; Reset the yas--dollar-regions
3764 (setq yas--dollar-regions nil)
3765 ;; protect escaped characters
3767 (yas--protect-escapes)
3768 ;; replace all backquoted expressions
3770 (goto-char parse-start)
3771 (yas--save-backquotes)
3772 ;; parse fields with {}
3774 (goto-char parse-start)
3775 (yas--field-parse-create snippet)
3776 ;; parse simple mirrors and fields
3778 (goto-char parse-start)
3779 (yas--simple-mirror-parse-create snippet)
3780 ;; parse mirror transforms
3782 (goto-char parse-start)
3783 (yas--transform-mirror-parse-create snippet)
3784 ;; calculate adjacencies of fields and mirrors
3786 (yas--calculate-adjacencies snippet)
3787 ;; Delete $-constructs
3789 (yas--delete-regions yas--dollar-regions)
3790 ;; restore backquoted expression values
3792 (yas--restore-backquotes)
3795 (goto-char parse-start)
3796 (yas--restore-escapes)
3797 ;; update mirrors for the first time
3799 (yas--update-mirrors snippet)
3800 ;; indent the best we can
3802 (goto-char parse-start)
3803 (yas--indent snippet)))
3805 (defun yas--indent-according-to-mode (snippet-markers)
3806 "Indent current line according to mode, preserving
3808 ;;; Apropos indenting problems....
3810 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3811 ;; is available. Some implementations of these functions delete text
3812 ;; before they insert. If there happens to be a marker just after
3813 ;; the text being deleted, the insertion actually happens after the
3814 ;; marker, which misplaces it.
3816 ;; This would also happen if we had used overlays with the
3817 ;; `front-advance' property set to nil.
3819 ;; This is why I have these `trouble-markers', they are the ones at
3820 ;; they are the ones at the first non-whitespace char at the line
3821 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3822 ;; we should be at the correct to restore them to. All other
3823 ;; non-trouble-markers have been *pushed* and don't need special
3826 (goto-char (yas--real-line-beginning))
3827 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3833 (indent-according-to-mode)
3834 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3836 (mapc #'(lambda (marker)
3837 (set-marker marker (point)))
3840 (defvar yas--indent-original-column nil)
3841 (defun yas--indent (snippet)
3842 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3843 ;; Look for those $>
3845 (while (re-search-forward "$>" nil t)
3846 (delete-region (match-beginning 0) (match-end 0))
3847 (when (not (eq yas-indent-line 'auto))
3848 (yas--indent-according-to-mode snippet-markers))))
3849 ;; Now do stuff for 'fixed and 'auto
3851 (cond ((eq yas-indent-line 'fixed)
3852 (while (and (zerop (forward-line))
3853 (zerop (current-column)))
3854 (indent-to-column yas--indent-original-column)))
3855 ((eq yas-indent-line 'auto)
3856 (let ((end (set-marker (make-marker) (point-max)))
3857 (indent-first-line-p yas-also-auto-indent-first-line))
3858 (while (and (zerop (if indent-first-line-p
3861 (setq indent-first-line-p nil))
3865 (yas--indent-according-to-mode snippet-markers))))
3869 (defun yas--collect-snippet-markers (snippet)
3870 "Make a list of all the markers used by SNIPPET."
3872 (dolist (field (yas--snippet-fields snippet))
3873 (push (yas--field-start field) markers)
3874 (push (yas--field-end field) markers)
3875 (dolist (mirror (yas--field-mirrors field))
3876 (push (yas--mirror-start mirror) markers)
3877 (push (yas--mirror-end mirror) markers)))
3878 (let ((snippet-exit (yas--snippet-exit snippet)))
3879 (when (and snippet-exit
3880 (marker-buffer (yas--exit-marker snippet-exit)))
3881 (push (yas--exit-marker snippet-exit) markers)))
3884 (defun yas--real-line-beginning ()
3885 (let ((c (char-after (line-beginning-position)))
3886 (n (line-beginning-position)))
3887 (while (or (eql c ?\ )
3890 (setq c (char-after n)))
3893 (defun yas--escape-string (escaped)
3894 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3896 (defun yas--protect-escapes (&optional text escaped)
3897 "Protect all escaped characters with their numeric ASCII value.
3899 With optional string TEXT do it in string instead of buffer."
3900 (let ((changed-text text)
3901 (text-provided-p text))
3902 (mapc #'(lambda (escaped)
3904 (yas--replace-all (concat "\\" (char-to-string escaped))
3905 (yas--escape-string escaped)
3906 (when text-provided-p changed-text))))
3907 (or escaped yas--escaped-characters))
3910 (defun yas--restore-escapes (&optional text escaped)
3911 "Restore all escaped characters from their numeric ASCII value.
3913 With optional string TEXT do it in string instead of the buffer."
3914 (let ((changed-text text)
3915 (text-provided-p text))
3916 (mapc #'(lambda (escaped)
3918 (yas--replace-all (yas--escape-string escaped)
3919 (char-to-string escaped)
3920 (when text-provided-p changed-text))))
3921 (or escaped yas--escaped-characters))
3924 (defun yas--save-backquotes ()
3925 "Save all the \"`(lisp-expression)`\"-style expression
3926 with their evaluated value into `yas--backquote-markers-and-strings'"
3927 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3928 (let ((current-string (match-string 1)) transformed)
3929 (delete-region (match-beginning 0) (match-end 0))
3930 (setq transformed (yas--eval-lisp (yas--read-lisp current-string)))
3931 (goto-char (match-beginning 0))
3933 (let ((marker (make-marker)))
3934 (insert "Y") ;; quite horrendous, I love it :)
3935 (set-marker marker (point))
3937 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3939 (defun yas--restore-backquotes ()
3940 "Replace all the markers in
3941 `yas--backquote-markers-and-strings' with their values"
3942 (while yas--backquote-markers-and-strings
3943 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3944 (marker (car marker-and-string))
3945 (string (cdr marker-and-string)))
3951 (set-marker marker nil)))))
3953 (defun yas--scan-sexps (from count)
3955 (with-syntax-table (standard-syntax-table)
3956 (scan-sexps from count))
3960 (defun yas--make-marker (pos)
3961 "Create a marker at POS with `nil' `marker-insertion-type'"
3962 (let ((marker (set-marker (make-marker) pos)))
3963 (set-marker-insertion-type marker nil)
3966 (defun yas--field-parse-create (snippet &optional parent-field)
3967 "Parse most field expressions, except for the simple one \"$n\".
3969 The following count as a field:
3971 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3973 * \"${n: text$(expression)}, the same with a lisp expression;
3974 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3976 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3978 When multiple expressions are found, only the last one counts."
3981 (while (re-search-forward yas--field-regexp nil t)
3982 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3983 (number (and (match-string-no-properties 1)
3984 (string-to-number (match-string-no-properties 1))))
3985 (brand-new-field (and real-match-end-0
3986 ;; break if on "$(" immediately
3987 ;; after the ":", this will be
3988 ;; caught as a mirror with
3990 (not (save-match-data
3991 (eq (string-match "$[ \t\n]*("
3992 (match-string-no-properties 2)) 0)))
3993 ;; allow ${0: some exit text}
3994 ;; (not (and number (zerop number)))
3995 (yas--make-field number
3996 (yas--make-marker (match-beginning 2))
3997 (yas--make-marker (1- real-match-end-0))
3999 (when brand-new-field
4000 (goto-char real-match-end-0)
4001 (push (cons (1- real-match-end-0) real-match-end-0)
4002 yas--dollar-regions)
4003 (push (cons (match-beginning 0) (match-beginning 2))
4004 yas--dollar-regions)
4005 (push brand-new-field (yas--snippet-fields snippet))
4008 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4009 (goto-char (point-min))
4010 (yas--field-parse-create snippet brand-new-field)))))))
4011 ;; if we entered from a parent field, now search for the
4012 ;; `yas--multi-dollar-lisp-expression-regexp'. THis is used for
4013 ;; primary field transformations
4017 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4018 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4019 ;; commit the primary field transformation if:
4021 ;; 1. we don't find it in yas--dollar-regions (a subnested
4022 ;; field) might have already caught it.
4024 ;; 2. we really make sure we have either two '$' or some
4025 ;; text and a '$' after the colon ':'. This is a FIXME: work
4026 ;; my regular expressions and end these ugly hacks.
4028 (when (and real-match-end-1
4029 (not (member (cons (match-beginning 0)
4031 yas--dollar-regions))
4033 (char-before (1- (match-beginning 1))))))
4034 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4036 (setf (yas--field-transform parent-field)
4037 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4038 (push (cons (match-beginning 0) real-match-end-1)
4039 yas--dollar-regions)))))))
4041 (defun yas--transform-mirror-parse-create (snippet)
4042 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
4043 (while (re-search-forward yas--transform-mirror-regexp nil t)
4044 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4045 (number (string-to-number (match-string-no-properties 1)))
4047 (not (zerop number))
4048 (yas--snippet-find-field snippet number)))
4050 (and real-match-end-0
4052 (yas--make-mirror (yas--make-marker (match-beginning 0))
4053 (yas--make-marker (match-beginning 0))
4055 (yas--restore-escapes
4056 (buffer-substring-no-properties (match-beginning 2)
4057 (1- real-match-end-0))))))))
4058 (when brand-new-mirror
4059 (push brand-new-mirror
4060 (yas--field-mirrors field))
4061 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4062 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4064 (defun yas--simple-mirror-parse-create (snippet)
4065 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
4066 (while (re-search-forward yas--simple-mirror-regexp nil t)
4067 (let ((number (string-to-number (match-string-no-properties 1))))
4068 (cond ((zerop number)
4070 (setf (yas--snippet-exit snippet)
4071 (yas--make-exit (yas--make-marker (match-end 0))))
4073 (goto-char (match-beginning 0))
4074 (when yas-wrap-around-region
4075 (cond (yas-selected-text
4076 (insert yas-selected-text))
4077 ((and (eq yas-wrap-around-region 'cua)
4080 (insert (prog1 (get-register ?0)
4081 (set-register ?0 nil))))))
4082 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4083 yas--dollar-regions)))
4085 (let ((field (yas--snippet-find-field snippet number)))
4087 (let ((brand-new-mirror (yas--make-mirror
4088 (yas--make-marker (match-beginning 0))
4089 (yas--make-marker (match-beginning 0))
4091 (push brand-new-mirror
4092 (yas--field-mirrors field))
4093 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4094 (push (yas--make-field number
4095 (yas--make-marker (match-beginning 0))
4096 (yas--make-marker (match-beginning 0))
4098 (yas--snippet-fields snippet))))
4099 (push (cons (match-beginning 0) (match-end 0))
4100 yas--dollar-regions))))))
4102 (defun yas--delete-regions (regions)
4103 "Sort disjuct REGIONS by start point, then delete from the back."
4104 (mapc #'(lambda (reg)
4105 (delete-region (car reg) (cdr reg)))
4108 (>= (car r1) (car r2))))))
4110 (defun yas--update-mirrors (snippet)
4111 "Updates all the mirrors of SNIPPET."
4113 (let* ((fields (copy-list (yas--snippet-fields snippet)))
4114 (field (car fields)))
4116 (dolist (mirror (yas--field-mirrors field))
4117 (let ((mirror-parent-field (yas--mirror-parent-field mirror)))
4118 ;; updatte this mirror
4120 (yas--mirror-update-display mirror field)
4121 ;; for mirrors-in-fields: schedule a possible
4122 ;; parent field for reupdting later on
4124 (when mirror-parent-field
4125 (add-to-list 'fields mirror-parent-field 'append #'eq))
4126 ;; `yas--place-overlays' is needed if the active field and
4127 ;; protected overlays have been changed because of insertions
4128 ;; in `yas--mirror-update-display'
4130 (when (eq field (yas--snippet-active-field snippet))
4131 (yas--place-overlays snippet field))))
4132 (setq fields (cdr fields))
4133 (setq field (car fields))))))
4135 (defun yas--mirror-update-display (mirror field)
4136 "Update MIRROR according to FIELD (and mirror transform)."
4138 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4139 (reflection (and (not (and mirror-parent-field
4140 (yas--field-modified-p mirror-parent-field)))
4141 (or (yas--apply-transform mirror field 'empty-on-nil)
4142 (yas--field-text-for-display field)))))
4143 (when (and reflection
4144 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4145 (yas--mirror-end mirror)))))
4146 (goto-char (yas--mirror-start mirror))
4147 (yas--inhibit-overlay-hooks
4148 (insert reflection))
4149 (if (> (yas--mirror-end mirror) (point))
4150 (delete-region (point) (yas--mirror-end mirror))
4151 (set-marker (yas--mirror-end mirror) (point))
4152 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4153 ;; super-special advance
4154 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4156 (defun yas--field-update-display (field snippet)
4157 "Much like `yas--mirror-update-display', but for fields"
4158 (when (yas--field-transform field)
4159 (let ((transformed (and (not (eq (yas--field-number field) 0))
4160 (yas--apply-transform field field)))
4162 (when (and transformed
4163 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4164 (yas--field-end field)))))
4165 (setf (yas--field-modified-p field) t)
4166 (goto-char (yas--field-start field))
4167 (yas--inhibit-overlay-hooks
4168 (insert transformed)
4169 (if (> (yas--field-end field) (point))
4170 (delete-region (point) (yas--field-end field))
4171 (set-marker (yas--field-end field) (point))
4172 (yas--advance-start-maybe (yas--field-next field) (point)))
4176 ;;; Post-command hook:
4178 (defun yas--post-command-handler ()
4179 "Handles various yasnippet conditions after each command."
4180 (cond (yas--protection-violation
4181 (goto-char yas--protection-violation)
4182 (setq yas--protection-violation nil))
4183 ((eq 'undo this-command)
4185 ;; After undo revival the correct field is sometimes not
4186 ;; restored correctly, this condition handles that
4188 (let* ((snippet (car (yas--snippets-at-point)))
4189 (target-field (and snippet
4190 (find-if-not #'(lambda (field)
4191 (yas--field-probably-deleted-p snippet field))
4193 (cons (yas--snippet-active-field snippet)
4194 (yas--snippet-fields snippet)))))))
4196 (yas--move-to-field snippet target-field))))
4197 ((not (yas--undo-in-progress))
4198 ;; When not in an undo, check if we must commit the snippet
4199 ;; (user exited it).
4200 (yas--check-commit-snippet))))
4204 ;; The docstrings for some functions are generated dynamically
4205 ;; depending on the context.
4207 (put 'yas-expand 'function-documentation
4208 '(yas--expand-from-trigger-key-doc))
4209 (defun yas--expand-from-trigger-key-doc ()
4210 "A doc synthethizer for `yas--expand-from-trigger-key-doc'."
4211 (let ((fallback-description
4212 (cond ((eq yas-fallback-behavior 'call-other-command)
4213 (let* ((yas-minor-mode nil)
4214 (fallback (key-binding (read-kbd-macro yas-trigger-key))))
4216 (format " call command `%s'." (pp-to-string fallback)))
4218 ((eq yas-fallback-behavior 'return-nil)
4221 ", defer to `yas--fallback-behaviour' :-)"))))
4222 (concat "Expand a snippet before point. If no snippet
4223 expansion is possible,"
4224 fallback-description
4225 "\n\nOptional argument FIELD is for non-interactive use and is an
4226 object satisfying `yas--field-p' to restrict the expansion to.")))
4228 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4229 (defun yas--expand-from-keymap-doc ()
4230 "A doc synthethizer for `yas--expand-from-keymap-doc'."
4231 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4232 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4233 (when (eq this-command 'describe-key)
4234 (let* ((vec (this-single-command-keys))
4235 (templates (mapcan #'(lambda (table)
4236 (yas--fetch table vec))
4237 (yas--get-snippet-tables)))
4238 (yas--direct-keymaps nil)
4239 (fallback (key-binding vec)))
4240 (concat "In this case, "
4242 (concat "these snippets are bound to this key:\n"
4243 (yas--template-pretty-list templates)
4244 "\n\nIf none of these expands, "))
4246 (format "fallback `%s' will be called." (pp-to-string fallback)))
4247 "no fallback keybinding is called."))))))
4249 (defun yas--template-pretty-list (templates)
4251 (yas-buffer-local-condition 'always))
4252 (dolist (plate templates)
4253 (setq acc (concat acc "\n*) "
4254 (propertize (concat "\\\\snippet `" (car plate) "'")
4255 'yasnippet (cdr plate)))))
4258 (define-button-type 'help-snippet-def
4259 :supertype 'help-xref
4260 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4261 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4263 (defun yas--snippet-description-finish-runonce ()
4264 "Final adjustments for the help buffer when snippets are concerned."
4265 (yas--create-snippet-xrefs)
4266 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4268 (defun yas--create-snippet-xrefs ()
4270 (goto-char (point-min))
4271 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4272 (let ((template (get-text-property (match-beginning 1)
4275 (help-xref-button 1 'help-snippet-def template)
4276 (kill-region (match-end 1) (match-end 0))
4277 (kill-region (match-beginning 0) (match-beginning 1)))))))
4279 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4280 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4282 Remaining args as in `yas-expand-snippet'."
4283 (let* ((table (gethash mode-symbol yas--tables))
4284 (yas--current-template (and table
4285 (gethash uuid (yas--table-uuidhash table)))))
4286 (when yas--current-template
4287 (yas-expand-snippet (yas--template-content yas--current-template)))))
4291 (defvar yas-verbosity 4
4292 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4294 (defun yas--message (level message &rest args)
4295 (when (> yas-verbosity level)
4296 (message (apply #'yas--format message args))))
4298 (defun yas--format (format-control &rest format-args)
4299 (apply #'format (concat "[yas] " format-control) format-args))
4306 ;; `locate-dominating-file'
4307 ;; `region-active-p'
4309 ;; added for compatibility in emacsen < 23
4310 (unless (>= emacs-major-version 23)
4311 (unless (fboundp 'region-active-p)
4312 (defun region-active-p () (and transient-mark-mode mark-active)))
4314 (unless (fboundp 'locate-dominating-file)
4315 (defvar locate-dominating-stop-dir-regexp
4316 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4317 "Regexp of directory names which stop the search in `locate-dominating-file'.
4318 Any directory whose name matches this regexp will be treated like
4319 a kind of root directory by `locate-dominating-file' which will stop its search
4320 when it bumps into it.
4321 The default regexp prevents fruitless and time-consuming attempts to find
4322 special files in directories in which filenames are interpreted as hostnames,
4323 or mount points potentially requiring authentication as a different user.")
4325 (defun locate-dominating-file (file name)
4326 "Look up the directory hierarchy from FILE for a file named NAME.
4327 Stop at the first parent directory containing a file NAME,
4328 and return the directory. Return nil if not found."
4329 ;; We used to use the above locate-dominating-files code, but the
4330 ;; directory-files call is very costly, so we're much better off doing
4331 ;; multiple calls using the code in here.
4333 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4334 ;; `name' in /home or in /.
4335 (setq file (abbreviate-file-name file))
4338 ;; `user' is not initialized outside the loop because
4339 ;; `file' may not exist, so we may have to walk up part of the
4340 ;; hierarchy before we find the "initial UUID".
4343 (while (not (or root
4345 ;; FIXME: Disabled this heuristic because it is sometimes
4347 ;; As a heuristic, we stop looking up the hierarchy of
4348 ;; directories as soon as we find a directory belonging
4349 ;; to another user. This should save us from looking in
4350 ;; things like /net and /afs. This assumes that all the
4351 ;; files inside a project belong to the same user.
4352 ;; (let ((prev-user user))
4353 ;; (setq user (nth 2 (file-attributes file)))
4354 ;; (and prev-user (not (equal user prev-user))))
4355 (string-match locate-dominating-stop-dir-regexp file)))
4356 (setq try (file-exists-p (expand-file-name name file)))
4357 (cond (try (setq root file))
4358 ((equal file (setq prev-file file
4359 file (file-name-directory
4360 (directory-file-name file))))
4364 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4365 ;; (when it execute forward-char) and interrupt the after change
4366 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4367 ;; invoked. Here's a way to reproduce it:
4369 ;; # open a *new* Emacs.
4370 ;; # load yasnippet.
4371 ;; # open a *new* .cpp file.
4372 ;; # input "inc" and press TAB to expand the snippet.
4373 ;; # select the `#include <...>` snippet.
4374 ;; # type inside `<>`
4376 (defadvice c-neutralize-syntax-in-CPP
4377 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4378 "Adviced `c-neutralize-syntax-in-CPP' to properly
4379 handle the end-of-buffer error fired in it by calling
4380 `forward-char' at the end of buffer."
4383 (error (message (error-message-string err)))))
4385 ;; disable c-electric-* serial command in YAS fields
4386 (add-hook 'c-mode-common-hook
4388 (dolist (k '(":" ">" ";" "<" "{" "}"))
4389 (define-key (symbol-value (make-local-variable 'yas-keymap))
4390 k 'self-insert-command))))
4392 ;;; Backward compatibility to to yasnippet <= 0.7
4393 (defvar yas--exported-syms '(;; `defcustom's
4396 yas-prompt-functions
4398 yas-also-auto-indent-first-line
4403 yas-skip-and-clear-key
4404 yas-triggers-in-field
4405 yas-fallback-behavior
4406 yas-choose-keys-first
4407 yas-choose-tables-first
4410 yas-wrap-around-region
4413 yas-expand-only-for-last-commands
4414 yas-field-highlight-face
4416 ;; these vars can be customized as well
4422 yas-after-exit-snippet-hook
4423 yas-before-expand-snippet-hook
4424 yas-buffer-local-condition
4426 ;; prompting functions
4431 yas-completing-prompt
4434 ;; interactive functions
4439 yas-direct-keymaps-reload
4443 yas-compile-directory
4446 yas-expand-from-trigger-key
4447 yas-expand-from-keymap
4449 yas-visit-snippet-file
4451 yas-load-snippet-buffer
4454 yas-next-field-or-maybe-expand
4459 yas-exit-all-snippets
4460 yas-skip-and-clear-or-delete-char
4462 ;; symbols that I "exported" for use
4463 ;; in snippets and hookage
4481 yas-default-from-field
4484 yas-define-condition-cache
4485 yas-hippie-try-expand
4487 ;; debug definitions
4488 ;; yas-debug-snippet-vars
4489 ;; yas-exterminate-package
4492 ;; testing definitions
4493 ;; yas-should-expand
4494 ;; yas-should-not-expand
4496 ;; yas-make-file-or-dirs
4498 ;; yas-saving-variables
4499 ;; yas-call-with-snippet-dirs
4500 ;; yas-with-snippet-dirs
4503 (dolist (sym yas--exported-syms)
4504 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4506 (make-obsolete-variable backported sym "yasnippet 0.8")
4507 (defvaralias backported sym))
4509 (make-obsolete backported sym "yasnippet 0.8")
4510 (defalias backported sym))))
4513 (provide 'yasnippet)
4515 ;;; yasnippet.el ends here