1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
5 ;; Maintainer: João Távora <joaotavora@gmail.com>
7 ;; Package-version: 0.8.0
8 ;; X-URL: http://github.com/capitaomorte/yasnippet
9 ;; Keywords: convenience, emulation
10 ;; URL: http://github.com/capitaomorte/yasnippet
11 ;; EmacsWiki: YaSnippetMode
13 ;; This program is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Basic steps to setup:
30 ;; (add-to-list 'load-path
31 ;; "~/path-to-yasnippet")
32 ;; (require 'yasnippet)
33 ;; (yas-global-mode 1)
36 ;; Interesting variables are:
40 ;; The directory where user-created snippets are to be
41 ;; stored. Can also be a list of directories. In that case,
42 ;; when used for bulk (re)loading of snippets (at startup or
43 ;; via `yas-reload-all'), directories appearing earlier in
44 ;; the list shadow other dir's snippets. Also, the first
45 ;; directory is taken as the default for storing the user's
48 ;; The deprecated `yas/root-directory' aliases this variable
49 ;; for backward-compatibility.
52 ;; Major commands are:
56 ;; Try to expand snippets before point. In `yas-minor-mode',
57 ;; this is normally bound to TAB, but you can customize it in
58 ;; `yas-minor-mode-map'.
60 ;; M-x yas-load-directory
62 ;; Prompts you for a directory hierarchy of snippets to load.
64 ;; M-x yas-activate-extra-mode
66 ;; Prompts you for an extra mode to add snippets for in the
69 ;; M-x yas-insert-snippet
71 ;; Prompts you for possible snippet expansion if that is
72 ;; possible according to buffer-local and snippet-local
73 ;; expansion conditions. With prefix argument, ignore these
76 ;; M-x yas-visit-snippet-file
78 ;; Prompts you for possible snippet expansions like
79 ;; `yas-insert-snippet', but instead of expanding it, takes
80 ;; you directly to the snippet definition's file, if it
83 ;; M-x yas-new-snippet
85 ;; Lets you create a new snippet file in the correct
86 ;; subdirectory of `yas-snippet-dirs', according to the
89 ;; M-x yas-load-snippet-buffer
91 ;; When editing a snippet, this loads the snippet. This is
92 ;; bound to "C-c C-c" while in the `snippet-mode' editing
95 ;; M-x yas-tryout-snippet
97 ;; When editing a snippet, this opens a new empty buffer,
98 ;; sets it to the appropriate major mode and inserts the
99 ;; snippet there, so you can see what it looks like. This is
100 ;; bound to "C-c C-t" while in `snippet-mode'.
102 ;; M-x yas-describe-tables
104 ;; Lists known snippets in a separate buffer. User is
105 ;; prompted as to whether only the currently active tables
106 ;; are to be displayed, or all the tables for all major
109 ;; If you have `dropdown-list' installed, you can optionally use it
110 ;; as the preferred "prompting method", putting in your .emacs file,
113 ;; (require 'dropdown-list)
114 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
116 ;; yas-completing-prompt))
118 ;; Also check out the customization group
120 ;; M-x customize-group RET yasnippet RET
122 ;; If you use the customization group to set variables
123 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
124 ;; "yasnippet.el" is present in the `load-path' *before* the
125 ;; `custom-set-variables' is executed in your .emacs file.
127 ;; For more information and detailed usage, refer to the project page:
128 ;; http://github.com/capitaomorte/yasnippet
138 (defvar yas--editing-template)
139 (defvar yas--guessed-modes)
140 (defvar yas--indent-original-column)
141 (defvar yas--scheduled-jit-loads)
143 (defvar yas-selected-text)
144 (defvar yas-verbosity)
145 (defvar yas--current-template)
148 ;;; User customizable variables
150 (defgroup yasnippet nil
151 "Yet Another Snippet extension"
154 (defvar yas--load-file-name load-file-name
155 "Store the filename that yasnippet.el was originally loaded from.")
157 (defcustom yas-snippet-dirs (remove nil
158 (list "~/.emacs.d/snippets"
159 (when yas--load-file-name
160 (concat (file-name-directory yas--load-file-name) "snippets"))))
161 "Directory or list of snippet dirs for each major mode.
163 The directory where user-created snippets are to be stored. Can
164 also be a list of directories. In that case, when used for
165 bulk (re)loading of snippets (at startup or via
166 `yas-reload-all'), directories appearing earlier in the list
167 shadow other dir's snippets. Also, the first directory is taken
168 as the default for storing the user's new snippets."
169 :type '(choice (string :tag "Single directory (string)")
170 (repeat :args (string) :tag "List of directories (strings)"))
173 :set #'(lambda (symbol new)
174 (let ((old (and (boundp symbol)
175 (symbol-value symbol))))
176 (set-default symbol new)
177 (unless (or (not (fboundp 'yas-reload-all))
181 (defun yas-snippet-dirs ()
182 "Return `yas-snippet-dirs' (which see) as a list."
183 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
187 (defcustom yas-new-snippet-default "\
188 # -*- mode: snippet; require-final-newline: nil -*-
190 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
191 # binding: ${4:direct-keybinding}}${5:
192 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
196 "Default snippet to use when creating a new snippet.
197 If nil, don't use any snippet."
201 (defcustom yas-prompt-functions '(yas-x-prompt
203 yas-completing-prompt
206 "Functions to prompt for keys, templates, etc interactively.
208 These functions are called with the following arguments:
210 - PROMPT: A string to prompt the user
212 - CHOICES: a list of strings or objects.
214 - optional DISPLAY-FN : A function that, when applied to each of
215 the objects in CHOICES will return a string.
217 The return value of any function you put here should be one of
218 the objects in CHOICES, properly formatted with DISPLAY-FN (if
221 - To signal that your particular style of prompting is
222 unavailable at the moment, you can also have the function return
225 - To signal that the user quit the prompting process, you can
228 (signal 'quit \"user quit!\")."
229 :type '(repeat function)
232 (defcustom yas-indent-line 'auto
233 "Controls indenting applied to a recent snippet expansion.
235 The following values are possible:
237 - `fixed' Indent the snippet to the current column;
239 - `auto' Indent each line of the snippet with `indent-according-to-mode'
241 Every other value means don't apply any snippet-side indentation
242 after expansion (the manual per-line \"$>\" indentation still
244 :type '(choice (const :tag "Nothing" nothing)
245 (const :tag "Fixed" fixed)
246 (const :tag "Auto" auto))
249 (defcustom yas-also-auto-indent-first-line nil
250 "Non-nil means also auto indent first line according to mode.
252 Naturally this is only valid when `yas-indent-line' is `auto'"
256 (defcustom yas-snippet-revival t
257 "Non-nil means re-activate snippet fields after undo/redo."
261 (defcustom yas-triggers-in-field nil
262 "If non-nil, allow stacked expansions (snippets inside snippets).
264 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
269 (defcustom yas-fallback-behavior 'call-other-command
270 "How to act when `yas-expand' does *not* expand a snippet.
272 - `call-other-command' means try to temporarily disable YASnippet
273 and call the next command bound to whatever key was used to
276 - nil or the symbol `return-nil' mean do nothing. (and
277 `yas-expand' returns nil)
279 - A Lisp form (apply COMMAND . ARGS) means interactively call
280 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
281 with ARGS as arguments."
282 :type '(choice (const :tag "Call previous command" call-other-command)
283 (const :tag "Do nothing" return-nil))
286 (defcustom yas-choose-keys-first nil
287 "If non-nil, prompt for snippet key first, then for template.
289 Otherwise prompts for all possible snippet names.
291 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
295 (defcustom yas-choose-tables-first nil
296 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
298 Otherwise, user chooses between the merging together of all
301 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
305 (defcustom yas-use-menu 'abbreviate
306 "Display a YASnippet menu in the menu bar.
308 When non-nil, submenus for each snippet table will be listed
309 under the menu \"Yasnippet\".
311 - If set to `abbreviate', only the current major-mode
312 menu and the modes set in `yas--extra-modes' are listed.
314 - If set to `full', every submenu is listed
316 - If set to `nil', hide the menu.
318 Any other non-nil value, every submenu is listed."
319 :type '(choice (const :tag "Full" full)
320 (const :tag "Abbreviate" abbreviate)
321 (const :tag "No menu" nil))
324 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
326 (char-to-string ?\x21E5))) ;; little ->| sign
328 "The text that will be used in menu to represent the trigger."
332 (defcustom yas-wrap-around-region nil
333 "If non-nil, snippet expansion wraps around selected region.
335 The wrapping occurs just before the snippet's exit marker. This
336 can be overridden on a per-snippet basis."
340 (defcustom yas-good-grace t
341 "If non-nil, don't raise errors in inline elisp evaluation.
343 An error string \"[yas] error\" is returned instead."
347 (defcustom yas-visit-from-menu nil
348 "If non-nil visit snippets's files from menu, instead of expanding them.
350 This can only work when snippets are loaded from files."
354 (defcustom yas-expand-only-for-last-commands nil
355 "List of `last-command' values to restrict tab-triggering to, or nil.
357 Leave this set at nil (the default) to be able to trigger an
358 expansion simply by placing the cursor after a valid tab trigger,
359 using whichever commands.
361 Optionally, set this to something like '(self-insert-command) if
362 you to wish restrict expansion to only happen when the last
363 letter of the snippet tab trigger was typed immediately before
364 the trigger key itself."
365 :type '(repeat function)
368 ;; Only two faces, and one of them shouldn't even be used...
370 (defface yas-field-highlight-face
371 '((t (:inherit 'region)))
372 "The face used to highlight the currently active field of a snippet"
375 (defface yas--field-debug-face
377 "The face used for debugging some overlays normally hidden"
381 ;;; User-visible variables
383 (defvar yas-keymap (let ((map (make-sparse-keymap)))
384 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
385 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
386 (define-key map [(shift tab)] 'yas-prev-field)
387 (define-key map [backtab] 'yas-prev-field)
388 (define-key map (kbd "C-g") 'yas-abort-snippet)
389 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
391 "The active keymap while a snippet expansion is in progress.")
393 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
394 "List of character syntaxes used to find a trigger key before point.
395 The list is tried in the order while scanning characters
396 backwards from point. For example, if the list is '(\"w\" \"w_\")
397 first look for trigger keys which are composed exclusively of
398 \"word\"-syntax characters, and then, if that fails, look for
399 keys which are either of \"word\" or \"symbol\"
400 syntax. Triggering after
404 will, according to the \"w\" element first try \"bar\". If that
405 isn't a trigger key, \"foo-bar\" is tried, respecting a second
408 (defvar yas-after-exit-snippet-hook
410 "Hooks to run after a snippet exited.
412 The hooks will be run in an environment where some variables bound to
415 `yas-snippet-beg' : The beginning of the region of the snippet.
417 `yas-snippet-end' : Similar to beg.
419 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
421 (defvar yas-before-expand-snippet-hook
423 "Hooks to run just before expanding a snippet.")
425 (defvar yas-buffer-local-condition
426 '(if (and (or (fourth (syntax-ppss))
427 (fifth (syntax-ppss)))
429 (eq this-command 'yas-expand-from-trigger-key))
430 '(require-snippet-condition . force-in-comment)
432 "Snippet expanding condition.
434 This variable is a Lisp form which is evaluated every time a
435 snippet expansion is attempted:
437 * If it evaluates to nil, no snippets can be expanded.
439 * If it evaluates to the a cons (require-snippet-condition
442 * Snippets bearing no \"# condition:\" directive are not
445 * Snippets bearing conditions that evaluate to nil (or
446 produce an error) won't be considered.
448 * If the snippet has a condition that evaluates to non-nil
451 * If REQUIREMENT is t, the snippet is considered
453 * If REQUIREMENT is `eq' RESULT, the snippet is
456 * Otherwise, the snippet is not considered.
458 * If it evaluates to the symbol 'always, all snippets are
459 considered for expansion, regardless of any conditions.
461 * If it evaluates to t or some other non-nil value
463 * Snippet bearing no conditions, or conditions that
464 evaluate to non-nil, are considered for expansion.
466 * Otherwise, the snippet is not considered.
468 Here's an example preventing snippets from being expanded from
469 inside comments, in `python-mode' only, with the exception of
470 snippets returning the symbol 'force-in-comment in their
473 (add-hook 'python-mode-hook
475 (setq yas-buffer-local-condition
476 '(if (python-in-string/comment)
477 '(require-snippet-condition . force-in-comment)
480 The default value is similar, it filters out potential snippet
481 expansions inside comments and string literals, unless the
482 snippet itself contains a condition that returns the symbol
483 `force-in-comment'.")
486 ;;; Internal variables
488 (defvar yas--version "0.8.0beta")
490 (defvar yas--menu-table (make-hash-table)
491 "A hash table of MAJOR-MODE symbols to menu keymaps.")
493 (defvar yas--known-modes
494 '(ruby-mode rst-mode markdown-mode)
495 "A list of mode which is well known but not part of Emacs.")
497 (defvar yas--escaped-characters
498 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
499 "List of characters which *might* need to be escaped.")
501 (defconst yas--field-regexp
502 "${\\([0-9]+:\\)?\\([^}]*\\)}"
503 "A regexp to *almost* recognize a field.")
505 (defconst yas--multi-dollar-lisp-expression-regexp
506 "$+[ \t\n]*\\(([^)]*)\\)"
507 "A regexp to *almost* recognize a \"$(...)\" expression.")
509 (defconst yas--backquote-lisp-expression-regexp
511 "A regexp to recognize a \"`lisp-expression`\" expression." )
513 (defconst yas--transform-mirror-regexp
514 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
515 "A regexp to *almost* recognize a mirror with a transform.")
517 (defconst yas--simple-mirror-regexp
519 "A regexp to recognize a simple mirror.")
521 (defvar yas--snippet-id-seed 0
522 "Contains the next id for a snippet.")
524 (defun yas--snippet-next-id ()
525 (let ((id yas--snippet-id-seed))
526 (incf yas--snippet-id-seed)
532 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
533 (defvar last-buffer-undo-list nil)
535 (defvar yas--minor-mode-menu nil
536 "Holds the YASnippet menu.")
538 (defvar yas-minor-mode-map
539 (let ((map (make-sparse-keymap)))
540 (define-key map [(tab)] 'yas-expand)
541 (define-key map (kbd "TAB") 'yas-expand)
542 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
543 (define-key map "\C-c&\C-n" 'yas-new-snippet)
544 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
546 "The keymap used when `yas-minor-mode' is active.")
548 (easy-menu-define yas--minor-mode-menu
550 "Menu used when `yas-minor-mode' is active."
551 '("YASnippet" :visible yas-use-menu
553 ["Expand trigger" yas-expand
554 :help "Possibly expand tab trigger before point"]
555 ["Insert at point..." yas-insert-snippet
556 :help "Prompt for an expandable snippet and expand it at point"]
557 ["New snippet..." yas-new-snippet
558 :help "Create a new snippet in an appropriate directory"]
559 ["Visit snippet file..." yas-visit-snippet-file
560 :help "Prompt for an expandable snippet and find its file"]
562 ("Snippet menu behaviour"
563 ["Visit snippets" (setq yas-visit-from-menu t)
564 :help "Visit snippets from the menu"
565 :active t :style radio :selected yas-visit-from-menu]
566 ["Expand snippets" (setq yas-visit-from-menu nil)
567 :help "Expand snippets from the menu"
568 :active t :style radio :selected (not yas-visit-from-menu)]
570 ["Show all known modes" (setq yas-use-menu 'full)
571 :help "Show one snippet submenu for each loaded table"
572 :active t :style radio :selected (eq yas-use-menu 'full)]
573 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
574 :help "Show only snippet submenus for the current active modes"
575 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
577 ["Auto" (setq yas-indent-line 'auto)
578 :help "Indent each line of the snippet with `indent-according-to-mode'"
579 :active t :style radio :selected (eq yas-indent-line 'auto)]
580 ["Fixed" (setq yas-indent-line 'fixed)
581 :help "Indent the snippet to the current column"
582 :active t :style radio :selected (eq yas-indent-line 'fixed)]
583 ["None" (setq yas-indent-line 'none)
584 :help "Don't apply any particular snippet indentation after expansion"
585 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
587 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
588 (not yas-also-auto-indent-first-line))
589 :help "When auto-indenting also, auto indent the first line menu"
590 :active (eq yas-indent-line 'auto)
591 :style toggle :selected yas-also-auto-indent-first-line]
594 ["System X-widget" (setq yas-prompt-functions
596 (remove 'yas-x-prompt
597 yas-prompt-functions)))
598 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
599 :active t :style radio :selected (eq (car yas-prompt-functions)
601 ["Dropdown-list" (setq yas-prompt-functions
602 (cons 'yas-dropdown-prompt
603 (remove 'yas-dropdown-prompt
604 yas-prompt-functions)))
605 :help "Use a special dropdown list"
606 :active t :style radio :selected (eq (car yas-prompt-functions)
607 'yas-dropdown-prompt)]
608 ["Ido" (setq yas-prompt-functions
609 (cons 'yas-ido-prompt
610 (remove 'yas-ido-prompt
611 yas-prompt-functions)))
612 :help "Use an ido-style minibuffer prompt"
613 :active t :style radio :selected (eq (car yas-prompt-functions)
615 ["Completing read" (setq yas-prompt-functions
616 (cons 'yas-completing-prompt
617 (remove 'yas-completing-prompt
618 yas-prompt-functions)))
619 :help "Use a normal minibuffer prompt"
620 :active t :style radio :selected (eq (car yas-prompt-functions)
621 'yas-completing-prompt)]
624 ["Wrap region in exit marker"
625 (setq yas-wrap-around-region
626 (not yas-wrap-around-region))
627 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
628 :style toggle :selected yas-wrap-around-region]
629 ["Allow stacked expansions "
630 (setq yas-triggers-in-field
631 (not yas-triggers-in-field))
632 :help "If non-nil allow snippets to be triggered inside other snippet fields"
633 :style toggle :selected yas-triggers-in-field]
634 ["Revive snippets on undo "
635 (setq yas-snippet-revival
636 (not yas-snippet-revival))
637 :help "If non-nil allow snippets to become active again after undo"
638 :style toggle :selected yas-snippet-revival]
641 (not yas-good-grace))
642 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
643 :style toggle :selected yas-good-grace]
646 ["Load snippets..." yas-load-directory
647 :help "Load snippets from a specific directory"]
648 ["Reload everything" yas-reload-all
649 :help "Cleanup stuff, reload snippets, rebuild menus"]
651 :help "Display some information about YASnippet"]))
653 (defvar yas--extra-modes nil
654 "An internal list of modes for which to also lookup snippets.
656 This variable probably makes more sense as buffer-local, so
657 ensure your use `make-local-variable' when you set it.")
658 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.8.1")
660 (defvar yas--tables (make-hash-table)
661 "A hash table of mode symbols to `yas--table' objects.")
663 (defvar yas--parents (make-hash-table)
664 "A hash table of mode symbols do lists of direct parent mode symbols.
666 This list is populated when reading the \".yas-parents\" files
667 found when traversing snippet directories with
668 `yas-load-directory'.
670 There might be additional parenting information stored in the
671 `derived-mode-parent' property of some mode symbols, but that is
674 (defvar yas--direct-keymaps (list)
675 "Keymap alist supporting direct snippet keybindings.
677 This variable is placed in `emulation-mode-map-alists'.
679 Its elements looks like (TABLE-NAME . KEYMAP). They're
680 instantiated on `yas-reload-all' but KEYMAP is added to only when
681 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
682 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
683 defined direct keybindings to the command
684 `yas-expand-from-keymap' which then which snippet to expand.")
686 (defun yas-direct-keymaps-reload ()
687 "Force reload the direct keybinding for active snippet tables."
689 (setq yas--direct-keymaps nil)
690 (maphash #'(lambda (name table)
691 (push (cons (intern (format "yas--direct-%s" name))
692 (yas--table-direct-keymap table))
693 yas--direct-keymaps))
696 (defun yas--modes-to-activate ()
697 "Compute list of mode symbols that are active for `yas-expand'
700 (setq dfs (lambda (mode &optional explored)
704 in (remove nil (cons (get mode
705 'derived-mode-parent)
706 (gethash mode yas--parents)))
708 unless (memq neighbour explored)
709 append (funcall dfs neighbour explored)))))
710 (remove-duplicates (append yas--extra-modes
711 (funcall dfs major-mode)))))
713 (defvar yas-minor-mode-hook nil
714 "Hook run when `yas-minor-mode' is turned on.")
717 (define-minor-mode yas-minor-mode
718 "Toggle YASnippet mode.
720 When YASnippet mode is enabled, `yas-expand', normally bound to
721 the TAB key, expands snippets of code depending on the major
724 With no argument, this command toggles the mode.
725 positive prefix argument turns on the mode.
726 Negative prefix argument turns off the mode.
729 \\{yas-minor-mode-map}"
731 ;; The indicator for the mode line.
734 (cond (yas-minor-mode
735 ;; Install the direct keymaps in `emulation-mode-map-alists'
736 ;; (we use `add-hook' even though it's not technically a hook,
737 ;; but it works). Then define variables named after modes to
738 ;; index `yas--direct-keymaps'.
740 ;; Also install the post-command-hook.
742 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
743 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
744 ;; Set the `yas--direct-%s' vars for direct keymap expansion
746 (dolist (mode (yas--modes-to-activate))
747 (let ((name (intern (format "yas--direct-%s" mode))))
748 (set-default name nil)
749 (set (make-local-variable name) t)))
752 (yas--load-pending-jits))
754 ;; Uninstall the direct keymaps and the post-command hook
756 (remove-hook 'post-command-hook 'yas--post-command-handler t)
757 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
759 (defun yas-activate-extra-mode (mode)
760 "Activates the snippets for the given `mode' in the buffer.
762 The function can be called in the hook of a minor mode to
763 activate snippets associated with that mode."
767 (maphash (lambda (k _)
768 (setq modes (cons (list k) modes)))
770 (setq symbol (completing-read
771 "Activate mode: " modes nil t))
773 (when (not (string= "" symbol))
776 (add-to-list (make-local-variable 'yas--extra-modes) mode)
777 (yas--load-pending-jits)))
779 (defun yas-deactivate-extra-mode (mode)
780 "Deactivates the snippets for the given `mode' in the buffer."
784 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
785 (set (make-local-variable 'yas--extra-modes)
789 (defvar yas-dont-activate '(minibufferp)
790 "If non-nil don't let `yas-global-mode' affect some buffers.
792 If a function of zero arguments, then its result is used.
794 If a list of functions, then all functions must return nil to
795 activate yas for this buffer.
797 In Emacsen <= 23, this variable is buffer-local. Because
798 `yas-minor-mode-on' is called by `yas-global-mode' after
799 executing the buffer's major mode hook, setting this variable
800 there is an effective way to define exceptions to the \"global\"
801 activation behaviour.
803 In Emacsen > 23, only the global value is used. To define
804 per-mode exceptions to the \"global\" activation behaviour, call
805 `yas-minor-mode' with a negative argument directily in the major
807 (unless (> emacs-major-version 23)
809 (make-variable-buffer-local 'yas-dont-activate)))
812 (defun yas-minor-mode-on ()
813 "Turn on YASnippet minor mode.
815 Honour `yas-dont-activate', which see."
817 ;; Check `yas-dont-activate'
818 (unless (cond ((functionp yas-dont-activate)
819 (funcall yas-dont-activate))
820 ((consp yas-dont-activate)
821 (some #'funcall yas-dont-activate))
826 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
830 (defun yas--global-mode-reload-with-jit-maybe ()
831 "Run `yas-reload-all' when `yas-global-mode' is on."
832 (when yas-global-mode (yas-reload-all)))
834 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
839 (defvar yas--font-lock-keywords
840 (append '(("^#.*$" . font-lock-comment-face))
841 lisp-font-lock-keywords-2
843 (0 font-lock-keyword-face)
844 (1 font-lock-string-face t))
846 (0 font-lock-keyword-face)
847 (1 font-lock-warning-face t))
848 ("${" . font-lock-keyword-face)
849 ("$[0-9]+?" . font-lock-preprocessor-face)
850 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
852 (0 font-lock-keyword-face)))))
854 (defvar snippet-mode-map
855 (let ((map (make-sparse-keymap)))
856 (easy-menu-define nil
858 "Menu used when snippet-mode is active."
860 (mapcar #'(lambda (ent)
862 (define-key map (third ent) (second ent)))
863 (vector (first ent) (second ent) t))
864 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
865 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
866 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
868 "The keymap used when `snippet-mode' is active.")
871 (define-derived-mode snippet-mode text-mode "Snippet"
872 "A mode for editing yasnippets"
873 (setq font-lock-defaults '(yas--font-lock-keywords))
874 (set (make-local-variable 'require-final-newline) nil)
875 (set (make-local-variable 'comment-start) "#")
876 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
880 ;;; Internal structs for template management
882 (defstruct (yas--template (:constructor yas--make-blank-template))
883 "A template for a snippet."
893 group ;; as dictated by the #group: directive or .yas-make-groups
894 perm-group ;; as dictated by `yas-define-menu'
898 (defun yas--populate-template (template &rest args)
899 "Helper function to populate TEMPLATE with properties."
902 (position (intern (substring (symbol-name (car args)) 1))
903 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
905 (setq args (cddr args)))
908 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
909 "A table to store snippets for a particular mode.
911 Has the following fields:
915 A symbol name normally corresponding to a major mode, but can
916 also be a pseudo major-mode to be used in
917 `yas-activate-extra-mode', for example.
921 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
922 a string or a vector, where the former is the snippet's trigger
923 and the latter means it's a direct keybinding. NAMEHASH is yet
924 another hash of (NAME . TEMPLATE) where NAME is the snippet's
925 name and TEMPLATE is a `yas--template' object.
927 `yas--table-direct-keymap'
929 A keymap for the snippets in this table that have direct
930 keybindings. This is kept in sync with the keyhash, i.e., all
931 the elements of the keyhash that are vectors appear here as
932 bindings to `yas-expand-from-keymap'.
934 `yas--table-uuidhash'
936 A hash table mapping snippets uuid's to the same `yas--template'
937 objects. A snippet uuid defaults to the snippet's name."
939 (hash (make-hash-table :test 'equal))
940 (uuidhash (make-hash-table :test 'equal))
942 (direct-keymap (make-sparse-keymap)))
944 (defun yas--get-template-by-uuid (mode uuid)
945 "Find the snippet template in MODE by its UUID."
946 (let* ((table (gethash mode yas--tables mode)))
948 (gethash uuid (yas--table-uuidhash table)))))
950 ;; Apropos storing/updating in TABLE, this works in two steps:
952 ;; 1. `yas--remove-template-by-uuid' removes any
953 ;; keyhash-namehash-template mappings from TABLE, grabbing the
954 ;; snippet by its uuid. Also removes mappings from TABLE's
955 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
956 ;; of potentially stale menu bindings right?.)
958 ;; 2. `yas--add-template' adds this all over again.
960 ;; Create a new or add to an existing keyhash-namehash mapping.
962 ;; For reference on understanding this, consider three snippet
965 ;; A: # name: The Foo
967 ;; # binding: C-c M-l
969 ;; B: # name: Mrs Foo
972 ;; C: # name: The Bar
973 ;; # binding: C-c M-l
978 ;; keyhash namehashes(3) yas--template structs(4)
979 ;; -----------------------------------------------------
982 ;; "foo" ---> "The Foo" ---> [yas--template A] |
983 ;; "Mrs Foo" ---> [yas--template B] |
985 ;; [C-c M-l] ---> "The Foo" -------------------------/
986 ;; "The Bar" ---> [yas--template C]
988 ;; "baz" ---> "Baz" ---> [yas--template D]
990 ;; Additionally, since uuid defaults to the name, we have a
991 ;; `yas--table-uuidhash' for TABLE
993 ;; uuidhash yas--template structs
994 ;; -------------------------------
995 ;; "The Foo" ---> [yas--template A]
996 ;; "Mrs Foo" ---> [yas--template B]
997 ;; "The Bar" ---> [yas--template C]
998 ;; "Baz" ---> [yas--template D]
1000 ;; FIXME: the more I look at this data-structure the more I think I'm
1001 ;; stupid. There has to be an easier way (but beware lots of code
1002 ;; depends on this).
1004 (defun yas--remove-template-by-uuid (table uuid)
1005 "Remove from TABLE a template identified by UUID."
1006 (let ((template (gethash uuid (yas--table-uuidhash table))))
1008 (let* ((name (yas--template-name template))
1010 ;; Remove the name from each of the targeted namehashes
1012 (maphash #'(lambda (k v)
1013 (let ((template (gethash name v)))
1015 (eq uuid (yas--template-uuid template)))
1017 (when (zerop (hash-table-count v))
1018 (push k empty-keys)))))
1019 (yas--table-hash table))
1020 ;; Remove the namehash themselves if they've become empty
1022 (dolist (key empty-keys)
1024 (define-key (yas--table-direct-keymap table) key nil))
1025 (remhash key (yas--table-hash table)))
1027 ;; Finally, remove the uuid from the uuidhash
1029 (remhash uuid (yas--table-uuidhash table))))))
1031 (defun yas--add-template (table template)
1032 "Store in TABLE the snippet template TEMPLATE.
1034 KEY can be a string (trigger key) of a vector (direct
1036 (let ((name (yas--template-name template))
1037 (key (yas--template-key template))
1038 (keybinding (yas--template-keybinding template))
1039 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1040 (dolist (k (remove nil (list key keybinding)))
1044 (yas--table-hash table))
1046 (make-hash-table :test 'equal)
1047 (yas--table-hash table))))
1049 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1051 ;; Update TABLE's `yas--table-uuidhash'
1052 (puthash (yas--template-uuid template)
1054 (yas--table-uuidhash table))))
1056 (defun yas--update-template (table template)
1057 "Add or update TEMPLATE in TABLE.
1059 Also takes care of adding and updating to the associated menu."
1060 ;; Remove from table by uuid
1062 (yas--remove-template-by-uuid table (yas--template-uuid template))
1063 ;; Add to table again
1065 (yas--add-template table template)
1066 ;; Take care of the menu
1068 (yas--update-template-menu table template))
1070 (defun yas--update-template-menu (table template)
1071 "Update every menu-related for TEMPLATE."
1072 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1073 (key (yas--template-key template))
1074 (keybinding (yas--template-keybinding template)))
1075 ;; The snippet might have changed name or keys, so update
1076 ;; user-visible strings
1078 (unless (eq (cdr menu-binding-pair) :none)
1079 ;; the menu item name
1081 (setf (cadar menu-binding-pair) (yas--template-name template))
1082 ;; the :keys information (also visible to the user)
1083 (setf (getf (cdr (car menu-binding-pair)) :keys)
1084 (or (and keybinding (key-description keybinding))
1085 (and key (concat key yas-trigger-symbol))))))
1086 (unless (yas--template-menu-managed-by-yas-define-menu template)
1088 (yas--menu-keymap-get-create (yas--table-mode table)
1089 (mapcar #'yas--table-mode
1090 (yas--table-parents table))))
1091 (group (yas--template-group template)))
1092 ;; Remove from menu keymap
1094 (assert menu-keymap)
1095 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1097 ;; Add necessary subgroups as necessary.
1099 (dolist (subgroup group)
1100 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1101 (unless (and subgroup-keymap
1102 (keymapp subgroup-keymap))
1103 (setq subgroup-keymap (make-sparse-keymap))
1104 (define-key menu-keymap (vector (make-symbol subgroup))
1105 `(menu-item ,subgroup ,subgroup-keymap)))
1106 (setq menu-keymap subgroup-keymap)))
1108 ;; Add this entry to the keymap
1110 (define-key menu-keymap
1111 (vector (make-symbol (yas--template-uuid template)))
1112 (car (yas--template-menu-binding-pair template))))))
1114 (defun yas--namehash-templates-alist (namehash)
1115 "Return NAMEHASH as an alist."
1117 (maphash #'(lambda (k v)
1118 (push (cons k v) alist))
1122 (defun yas--fetch (table key)
1123 "Fetch templates in TABLE by KEY.
1125 Return a list of cons (NAME . TEMPLATE) where NAME is a
1126 string and TEMPLATE is a `yas--template' structure."
1127 (let* ((keyhash (yas--table-hash table))
1128 (namehash (and keyhash (gethash key keyhash))))
1130 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1133 ;;; Filtering/condition logic
1135 (defun yas--eval-condition (condition)
1142 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1146 (defun yas--filter-templates-by-condition (templates)
1147 "Filter the templates using the applicable condition.
1149 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1150 string and TEMPLATE is a `yas--template' structure.
1152 This function implements the rules described in
1153 `yas-buffer-local-condition'. See that variables documentation."
1154 (let ((requirement (yas--require-template-specific-condition-p)))
1155 (if (eq requirement 'always)
1157 (remove-if-not #'(lambda (pair)
1158 (yas--template-can-expand-p
1159 (yas--template-condition (cdr pair)) requirement))
1162 (defun yas--require-template-specific-condition-p ()
1163 "Decide if this buffer requests/requires snippet-specific
1164 conditions to filter out potential expansions."
1165 (if (eq 'always yas-buffer-local-condition)
1167 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1168 (yas--eval-condition yas-buffer-local-condition))
1169 yas-buffer-local-condition)))
1170 (when local-condition
1171 (if (eq local-condition t)
1173 (and (consp local-condition)
1174 (eq 'require-snippet-condition (car local-condition))
1175 (symbolp (cdr local-condition))
1176 (cdr local-condition)))))))
1178 (defun yas--template-can-expand-p (condition requirement)
1179 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1180 (let* ((result (or (null condition)
1181 (yas--eval-condition condition))))
1182 (cond ((eq requirement t)
1185 (eq requirement result)))))
1187 (defun yas--table-templates (table)
1190 (maphash #'(lambda (_key namehash)
1191 (maphash #'(lambda (name template)
1192 (push (cons name template) acc))
1194 (yas--table-hash table))
1195 (yas--filter-templates-by-condition acc))))
1197 (defun yas--current-key ()
1198 "Get the key under current position.
1199 A key is used to find the template of a snippet in the current snippet-table."
1200 (let ((start (point))
1202 (syntaxes yas-key-syntaxes)
1206 (while (and (not done) syntaxes)
1207 (setq syntax (car syntaxes))
1208 (setq syntaxes (cdr syntaxes))
1210 (skip-syntax-backward syntax)
1211 (setq start (point)))
1213 (mapcan #'(lambda (table)
1214 (yas--fetch table (buffer-substring-no-properties start end)))
1215 (yas--get-snippet-tables)))
1224 (defun yas--table-all-keys (table)
1225 "Get trigger keys of all active snippets in TABLE."
1227 (maphash #'(lambda (key namehash)
1228 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1230 (yas--table-hash table))
1233 (defun yas--table-mode (table)
1234 (intern (yas--table-name table)))
1237 ;;; Internal functions and macros:
1239 (defun yas--real-mode? (mode)
1240 "Try to find out if MODE is a real mode.
1242 The MODE bound to a function (like `c-mode') is considered real
1243 mode. Other well known mode like `ruby-mode' which is not part of
1244 Emacs might not bound to a function until it is loaded. So
1245 yasnippet keeps a list of modes like this to help the judgment."
1247 (find mode yas--known-modes)))
1249 (defun yas--handle-error (err)
1250 "Handle error depending on value of `yas-good-grace'."
1251 (let ((msg (yas--format "elisp error: %s" (error-message-string err))))
1252 (if yas-good-grace msg
1255 (defun yas--eval-lisp (form)
1256 "Evaluate FORM and convert the result to string."
1257 (let ((retval (catch 'yas--exception
1263 (let ((result (eval form)))
1265 (format "%s" result))))))
1266 (error (yas--handle-error err))))))
1267 (when (and (consp retval)
1268 (eq 'yas--exception (car retval)))
1269 (error (cdr retval)))
1272 (defun yas--eval-lisp-no-saves (form)
1275 (error (yas--handle-error err))))
1277 (defun yas--read-lisp (string &optional nil-on-error)
1278 "Read STRING as a elisp expression and return it.
1280 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1281 return an expression that when evaluated will issue an error."
1284 (error (and (not nil-on-error)
1285 `(error (error-message-string ,err))))))
1287 (defun yas--read-keybinding (keybinding)
1288 "Read KEYBINDING as a snippet keybinding, return a vector."
1289 (when (and keybinding
1290 (not (string-match "keybinding" keybinding)))
1292 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1294 (read-kbd-macro keybinding 'need-vector))))
1297 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1298 keybinding (error-message-string err))
1301 (defun yas--table-get-create (mode)
1302 "Get or create the snippet table corresponding to MODE."
1303 (let ((table (gethash mode
1306 (setq table (yas--make-snippet-table (symbol-name mode)))
1307 (puthash mode table yas--tables)
1308 (push (cons (intern (format "yas--direct-%s" mode))
1309 (yas--table-direct-keymap table))
1310 yas--direct-keymaps))
1313 (defun yas--get-snippet-tables ()
1314 "Get snippet tables for current buffer.
1316 Return a list of `yas--table' objects. The list of modes to
1317 consider is returned by `yas--modes-to-activate'"
1319 (mapcar #'(lambda (name)
1320 (gethash name yas--tables))
1321 (yas--modes-to-activate))))
1323 (defun yas--menu-keymap-get-create (mode &optional parents)
1324 "Get or create the menu keymap for MODE and its PARENTS.
1326 This may very well create a plethora of menu keymaps and arrange
1327 them all in `yas--menu-table'"
1328 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1329 (puthash mode (make-sparse-keymap) yas--menu-table))))
1330 (mapc #'yas--menu-keymap-get-create parents)
1331 (define-key yas--minor-mode-menu (vector mode)
1332 `(menu-item ,(symbol-name mode) ,menu-keymap
1333 :visible (yas--show-menu-p ',mode)))
1337 (defmacro yas--called-interactively-p (&optional kind)
1338 "A backward-compatible version of `called-interactively-p'.
1340 Optional KIND is as documented at `called-interactively-p'
1341 in GNU Emacs 24.1 or higher."
1342 (if (string< emacs-version "24.1")
1343 '(called-interactively-p)
1344 `(called-interactively-p ,kind)))
1347 ;;; Template-related and snippet loading functions
1349 (defun yas--parse-template (&optional file)
1350 "Parse the template in the current buffer.
1352 Optional FILE is the absolute file name of the file being
1355 Optional GROUP is the group where the template is to go,
1356 otherwise we attempt to calculate it from FILE.
1358 Return a snippet-definition, i.e. a list
1360 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1362 If the buffer contains a line of \"# --\" then the contents above
1363 this line are ignored. Directives can set most of these with the syntax:
1365 # directive-name : directive-value
1367 Here's a list of currently recognized directives:
1378 (goto-char (point-min))
1379 (let* ((type 'snippet)
1381 (file-name-nondirectory file)))
1387 (yas--calculate-group file)))
1391 (if (re-search-forward "^# --\n" nil t)
1392 (progn (setq template
1393 (buffer-substring-no-properties (point)
1395 (setq bound (point))
1396 (goto-char (point-min))
1397 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1398 (when (string= "uuid" (match-string-no-properties 1))
1399 (setq uuid (match-string-no-properties 2)))
1400 (when (string= "type" (match-string-no-properties 1))
1401 (setq type (if (string= "command" (match-string-no-properties 2))
1404 (when (string= "key" (match-string-no-properties 1))
1405 (setq key (match-string-no-properties 2)))
1406 (when (string= "name" (match-string-no-properties 1))
1407 (setq name (match-string-no-properties 2)))
1408 (when (string= "condition" (match-string-no-properties 1))
1409 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1410 (when (string= "group" (match-string-no-properties 1))
1411 (setq group (match-string-no-properties 2)))
1412 (when (string= "expand-env" (match-string-no-properties 1))
1413 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1415 (when (string= "binding" (match-string-no-properties 1))
1416 (setq binding (match-string-no-properties 2)))))
1418 (buffer-substring-no-properties (point-min) (point-max))))
1419 (unless (or key binding)
1420 (setq key (and file (file-name-nondirectory file))))
1421 (when (eq type 'command)
1422 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1424 (setq group (split-string group "\\.")))
1425 (list key template name condition group expand-env file binding uuid)))
1427 (defun yas--calculate-group (file)
1428 "Calculate the group for snippet file path FILE."
1429 (let* ((dominating-dir (locate-dominating-file file
1430 ".yas-make-groups"))
1431 (extra-path (and dominating-dir
1432 (replace-regexp-in-string (concat "^"
1433 (expand-file-name dominating-dir))
1435 (expand-file-name file))))
1436 (extra-dir (and extra-path
1437 (file-name-directory extra-path)))
1438 (group (and extra-dir
1439 (replace-regexp-in-string "/"
1441 (directory-file-name extra-dir)))))
1444 (defun yas--subdirs (directory &optional filep)
1445 "Return subdirs or files of DIRECTORY according to FILEP."
1446 (remove-if (lambda (file)
1447 (or (string-match "^\\."
1448 (file-name-nondirectory file))
1449 (string-match "^#.*#$"
1450 (file-name-nondirectory file))
1452 (file-name-nondirectory file))
1454 (file-directory-p file)
1455 (not (file-directory-p file)))))
1456 (directory-files directory t)))
1458 (defun yas--make-menu-binding (template)
1459 (let ((mode (yas--table-mode (yas--template-table template))))
1460 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1462 (defun yas--expand-or-visit-from-menu (mode uuid)
1463 (let* ((table (yas--table-get-create mode))
1464 (yas--current-template (and table
1465 (gethash uuid (yas--table-uuidhash table)))))
1466 (when yas--current-template
1467 (if yas-visit-from-menu
1468 (yas--visit-snippet-file-1 yas--current-template)
1469 (let ((where (if (region-active-p)
1470 (cons (region-beginning) (region-end))
1471 (cons (point) (point)))))
1472 (yas-expand-snippet (yas--template-content yas--current-template)
1475 (yas--template-expand-env yas--current-template)))))))
1477 (defun yas--key-from-desc (text)
1478 "Return a yasnippet key from a description string TEXT."
1479 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1482 ;;; Popping up for keys and templates
1484 (defun yas--prompt-for-template (templates &optional prompt)
1485 "Interactively choose a template from the list TEMPLATES.
1487 TEMPLATES is a list of `yas--template'.
1489 Optional PROMPT sets the prompt to use."
1492 (sort templates #'(lambda (t1 t2)
1493 (< (length (yas--template-name t1))
1494 (length (yas--template-name t2))))))
1495 (some #'(lambda (fn)
1496 (funcall fn (or prompt "Choose a snippet: ")
1498 #'yas--template-name))
1499 yas-prompt-functions)))
1501 (defun yas--prompt-for-keys (keys &optional prompt)
1502 "Interactively choose a template key from the list KEYS.
1504 Optional PROMPT sets the prompt to use."
1506 (some #'(lambda (fn)
1507 (funcall fn (or prompt "Choose a snippet key: ") keys))
1508 yas-prompt-functions)))
1510 (defun yas--prompt-for-table (tables &optional prompt)
1511 "Interactively choose a table from the list TABLES.
1513 Optional PROMPT sets the prompt to use."
1515 (some #'(lambda (fn)
1516 (funcall fn (or prompt "Choose a snippet table: ")
1519 yas-prompt-functions)))
1521 (defun yas-x-prompt (prompt choices &optional display-fn)
1522 "Display choices in a x-window prompt."
1523 (when (and window-system choices)
1526 (if (fboundp 'posn-at-point)
1527 (let ((x-y (posn-x-y (posn-at-point (point)))))
1528 (list (list (+ (car x-y) 10)
1533 ,@(mapcar* (lambda (c d) `(,(concat " " d) . ,c))
1535 (if display-fn (mapcar display-fn choices) choices)))))
1538 (defun yas-ido-prompt (prompt choices &optional display-fn)
1539 (when (and (fboundp 'ido-completing-read)
1540 (or (>= emacs-major-version 24)
1542 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1544 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1545 (when (fboundp 'dropdown-list)
1546 (let* ((formatted-choices
1547 (if display-fn (mapcar display-fn choices) choices))
1548 (n (dropdown-list formatted-choices)))
1549 (if n (nth n choices)
1552 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1553 (let* ((formatted-choices
1554 (if display-fn (mapcar display-fn choices) choices))
1555 (chosen (funcall (or completion-fn #'completing-read)
1556 prompt formatted-choices
1557 nil 'require-match nil nil)))
1558 (if (eq choices formatted-choices)
1560 (nth (or (position chosen formatted-choices :test #'string=) 0)
1563 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1567 ;;; Defining snippets
1568 ;; This consists of creating and registering `yas--template' objects in the
1572 (defvar yas--creating-compiled-snippets nil)
1574 (defun yas--define-snippets-1 (snippet snippet-table)
1575 "Helper for `yas-define-snippets'."
1576 ;; X) Calculate some more defaults on the values returned by
1577 ;; `yas--parse-template'.
1579 (let* ((file (seventh snippet))
1581 (name (or (third snippet)
1583 (file-name-directory file))))
1584 (condition (fourth snippet))
1585 (group (fifth snippet))
1586 (keybinding (yas--read-keybinding (eighth snippet)))
1587 (uuid (or (ninth snippet)
1589 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1590 (yas--make-blank-template))))
1591 ;; X) populate the template object
1593 (yas--populate-template template
1594 :table snippet-table
1596 :content (second snippet)
1599 :condition condition
1600 :expand-env (sixth snippet)
1601 :file (seventh snippet)
1602 :keybinding keybinding
1604 ;; X) Update this template in the appropriate table. This step
1605 ;; also will take care of adding the key indicators in the
1606 ;; templates menu entry, if any
1608 (yas--update-template snippet-table template)
1609 ;; X) Return the template
1614 (defun yas-define-snippets (mode snippets)
1615 "Define SNIPPETS for MODE.
1617 SNIPPETS is a list of snippet definitions, each taking the
1620 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1622 Within these, only KEY and TEMPLATE are actually mandatory.
1624 TEMPLATE might be a Lisp form or a string, depending on whether
1625 this is a snippet or a snippet-command.
1627 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1628 been `yas--read-lisp'-ed and will eventually be
1629 `yas--eval-lisp'-ed.
1631 The remaining elements are strings.
1633 FILE is probably of very little use if you're programatically
1636 UUID is the snippets \"unique-id\". Loading a second snippet file
1637 with the same uuid replaced the previous snippet.
1639 You can use `yas--parse-template' to return such lists based on
1640 the current buffers contents."
1641 (if yas--creating-compiled-snippets
1643 (insert ";;; Snippet definitions:\n;;;\n")
1644 (let ((literal-snippets (list))
1646 (dolist (snippet snippets)
1647 (let ((key (nth 0 snippet))
1648 (template-content (nth 1 snippet))
1649 (name (nth 2 snippet))
1650 (condition (nth 3 snippet))
1651 (group (nth 4 snippet))
1652 (expand-env (nth 5 snippet))
1653 (file nil) ;; omit on purpose
1654 (binding (nth 7 snippet))
1655 (uuid (nth 8 snippet)))
1666 (insert (pp-to-string
1667 `(yas-define-snippets ',mode ',literal-snippets)))
1670 (let ((snippet-table (yas--table-get-create mode))
1672 (dolist (snippet snippets)
1673 (setq template (yas--define-snippets-1 snippet
1678 ;;; Loading snippets from files
1680 (defun yas--load-yas-setup-file (file)
1681 (if (not yas--creating-compiled-snippets)
1683 (load file 'noerror)
1684 (let ((elfile (concat file ".el")))
1685 (when (file-exists-p elfile)
1686 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1687 (insert-file-contents elfile)
1688 (goto-char (point-max))))))
1690 (defun yas--define-parents (mode parents)
1691 "Add PARENTS to the list of MODE's parents."
1692 (puthash mode (remove-duplicates
1694 (gethash mode yas--parents)))
1697 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1698 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1700 Below TOP-LEVEL-DIR each directory should be a mode name.
1702 Optional USE-JIT use jit-loading of snippets."
1703 (interactive "DSelect the root directory: ni\np")
1704 (unless yas-snippet-dirs
1705 (setq yas-snippet-dirs top-level-dir))
1706 (dolist (dir (yas--subdirs top-level-dir))
1707 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1708 (concat dir "/dummy")))
1709 (mode-sym (car major-mode-and-parents))
1710 (parents (cdr major-mode-and-parents)))
1711 ;; Attention: The parents and the menus are already defined
1712 ;; here, even if the snippets are later jit-loaded.
1714 ;; * We need to know the parents at this point since entering a
1715 ;; given mode should jit load for its parents
1716 ;; immediately. This could be reviewed, the parents could be
1717 ;; discovered just-in-time-as well
1719 ;; * We need to create the menus here to support the `full'
1720 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1722 (yas--define-parents mode-sym parents)
1723 (yas--menu-keymap-get-create mode-sym)
1724 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1725 (yas--load-directory-1 ',dir ',mode-sym))))
1727 (not (some #'(lambda (buffer)
1728 (with-current-buffer buffer
1729 ;; FIXME: Shouldn't this use derived-mode-p?
1730 (when (eq major-mode mode-sym)
1731 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1734 (yas--schedule-jit mode-sym fun)
1737 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1739 (defun yas--load-directory-1 (directory mode-sym)
1740 "Recursively load snippet templates from DIRECTORY."
1741 (if yas--creating-compiled-snippets
1742 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1744 (with-temp-file output-file
1745 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1747 (yas--load-directory-2 directory mode-sym)
1748 (insert (format ";;; Do not edit! File generated at %s\n"
1749 (current-time-string)))))
1751 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1752 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1753 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1754 (yas--message 2 "Loading snippet files from %s" directory)
1755 (yas--load-directory-2 directory mode-sym)))))
1757 (defun yas--load-directory-2 (directory mode-sym)
1758 ;; Load .yas-setup.el files wherever we find them
1760 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1761 (let* ((default-directory directory)
1763 ;; load the snippet files
1766 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1767 (when (file-readable-p file)
1768 (insert-file-contents file nil nil nil t)
1769 (push (yas--parse-template file)
1772 (yas-define-snippets mode-sym
1774 ;; now recurse to a lower level
1776 (dolist (subdir (yas--subdirs directory))
1777 (yas--load-directory-2 subdir
1780 (defun yas--load-snippet-dirs (&optional nojit)
1781 "Reload the directories listed in `yas-snippet-dirs' or
1782 prompt the user to select one."
1784 (if yas-snippet-dirs
1785 (dolist (directory (reverse (yas-snippet-dirs)))
1786 (cond ((file-directory-p directory)
1787 (yas-load-directory directory (not nojit))
1789 (yas--message 3 "Loaded %s" directory)
1790 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1792 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1793 (call-interactively 'yas-load-directory))
1796 (defun yas-reload-all (&optional interactive)
1797 "Reload all snippets and rebuild the YASnippet menu.
1799 When called interactively force immediate reload of all known
1800 snippets under `yas-snippet-dirs', otherwise use just-in-time
1805 (snippet-editing-buffers
1806 (remove-if-not #'(lambda (buffer)
1807 (with-current-buffer buffer yas--editing-template))
1809 ;; Warn if there are buffers visiting snippets, since reloading will break
1810 ;; any on-line editing of those buffers.
1812 (when snippet-editing-buffers
1814 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1815 (mapc #'kill-buffer snippet-editing-buffers)
1816 (yas--message 1 "Aborted reload...")
1818 ;; in a non-interactive use, at least set
1819 ;; `yas--editing-template' to nil, make it guess it next time around
1820 (mapc #'(lambda (buffer)
1821 (with-current-buffer buffer
1822 (kill-local-variable 'yas--editing-template)))
1825 ;; Empty all snippet tables and parenting info
1827 (setq yas--tables (make-hash-table))
1828 (setq yas--parents (make-hash-table))
1830 ;; Before killing `yas--menu-table' use its keys to cleanup the
1831 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1832 ;; up `yas-minor-mode-map', which points to it)
1834 (maphash #'(lambda (menu-symbol _keymap)
1835 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1837 ;; Now empty `yas--menu-table' as well
1838 (setq yas--menu-table (make-hash-table))
1840 ;; Cancel all pending 'yas--scheduled-jit-loads'
1842 (setq yas--scheduled-jit-loads (make-hash-table))
1844 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1845 ;; the user to select one.
1847 (setq errors (yas--load-snippet-dirs interactive))
1848 ;; Reload the direct keybindings
1850 (yas-direct-keymaps-reload)
1852 (run-hooks 'yas-after-reload-hook)
1853 (yas--message 3 "Reloaded everything%s...%s."
1854 (if interactive "" " (snippets will load just-in-time)")
1855 (if errors " (some errors, check *Messages*)" "")))))
1857 (defvar yas-after-reload-hook nil
1858 "Hooks run after `yas-reload-all'.")
1860 (defun yas--load-pending-jits ()
1861 (dolist (mode (yas--modes-to-activate))
1862 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1863 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1865 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1867 (remhash mode yas--scheduled-jit-loads))))
1869 ;; (when (<= emacs-major-version 22)
1870 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1872 (defun yas--quote-string (string)
1873 "Escape and quote STRING.
1874 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1876 (replace-regexp-in-string "[\\\"]"
1882 ;;; Snippet compilation function
1884 (defun yas--initialize ()
1885 "For backward compatibility, enable `yas-minor-mode' globally."
1886 (yas-global-mode 1))
1888 (defun yas-compile-directory (top-level-dir)
1889 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1891 This works by stubbing a few functions, then calling
1892 `yas-load-directory'."
1893 (interactive "DTop level snippet directory?")
1894 (let ((yas--creating-compiled-snippets t))
1895 (yas-load-directory top-level-dir nil)))
1897 (defun yas-recompile-all ()
1898 "Compile every dir in `yas-snippet-dirs'."
1900 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1906 (defvar yas--scheduled-jit-loads (make-hash-table)
1907 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1909 (defun yas--schedule-jit (mode fun)
1910 (push fun (gethash mode yas--scheduled-jit-loads)))
1914 ;;; Some user level functions
1918 (message (concat "yasnippet (version "
1920 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1923 ;;; Apropos snippet menu:
1925 ;; The snippet menu keymaps are store by mode in hash table called
1926 ;; `yas--menu-table'. They are linked to the main menu in
1927 ;; `yas--menu-keymap-get-create' and are initially created empty,
1928 ;; reflecting the table hierarchy.
1930 ;; They can be populated in two mutually exclusive ways: (1) by
1931 ;; reading `yas--template-group', which in turn is populated by the "#
1932 ;; group:" directives of the snippets or the ".yas-make-groups" file
1933 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1934 ;; menu structure based on snippets uuids.
1936 ;; Both situations are handled in `yas--update-template-menu', which
1937 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1938 ;; that can tell between the two situations.
1942 ;; * if `yas-define-menu' is used it must run before
1943 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1944 ;; duplicate entries. The `yas--template' objects are created in
1945 ;; `yas-define-menu', holding nothing but the menu entry,
1946 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1947 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1948 ;; part is then stored in the menu keymap itself which make the item
1949 ;; appear to the user. These limitations could probably be revised.
1951 ;; * The `yas--template-perm-group' slot is only used in
1952 ;; `yas-describe-tables'.
1954 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1955 "Get TEMPLATE's menu binding or assign it a new one.
1957 TYPE may be `:stay', signaling this menu binding should be
1958 static in the menu."
1959 (or (yas--template-menu-binding-pair template)
1960 (let (;; (key (yas--template-key template))
1961 ;; (keybinding (yas--template-keybinding template))
1963 (setf (yas--template-menu-binding-pair template)
1964 (cons `(menu-item ,(or (yas--template-name template)
1965 (yas--template-uuid template))
1966 ,(yas--make-menu-binding template)
1969 (defun yas--template-menu-managed-by-yas-define-menu (template)
1970 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
1971 (cdr (yas--template-menu-binding-pair template)))
1974 (defun yas--show-menu-p (mode)
1975 (cond ((eq yas-use-menu 'abbreviate)
1977 (mapcar #'(lambda (table)
1978 (yas--table-mode table))
1979 (yas--get-snippet-tables))))
1982 (defun yas--delete-from-keymap (keymap uuid)
1983 "Recursively delete items with UUID from KEYMAP and its submenus."
1985 ;; XXX: This used to skip any submenus named \"parent mode\"
1987 ;; First of all, recursively enter submenus, i.e. the tree is
1988 ;; searched depth first so that stale submenus can be found in the
1991 (mapc #'(lambda (item)
1992 (when (and (listp (cdr item))
1993 (keymapp (third (cdr item))))
1994 (yas--delete-from-keymap (third (cdr item)) uuid)))
1996 ;; Set the uuid entry to nil
1998 (define-key keymap (vector (make-symbol uuid)) nil)
1999 ;; Destructively modify keymap
2001 (setcdr keymap (delete-if #'(lambda (item)
2002 (or (null (cdr item))
2003 (and (keymapp (third (cdr item)))
2004 (null (cdr (third (cdr item)))))))
2007 (defun yas-define-menu (mode menu &optional omit-items)
2008 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2010 MENU is a list, its elements can be:
2012 - (yas-item UUID) : Creates an entry the snippet identified with
2013 UUID. The menu entry for a snippet thus identified is
2014 permanent, i.e. it will never move (be reordered) in the menu.
2016 - (yas-separator) : Creates a separator
2018 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2019 SUBMENU has the same form as MENU. NAME is also added to the
2020 list of groups of the snippets defined thereafter.
2022 OMIT-ITEMS is a list of snippet uuid's that will always be
2023 omitted from MODE's menu, even if they're manually loaded."
2024 (let* ((table (yas--table-get-create mode))
2025 (hash (yas--table-uuidhash table)))
2026 (yas--define-menu-1 table
2027 (yas--menu-keymap-get-create mode)
2030 (dolist (uuid omit-items)
2031 (let ((template (or (gethash uuid hash)
2032 (yas--populate-template (puthash uuid
2033 (yas--make-blank-template)
2037 (setf (yas--template-menu-binding-pair template) (cons nil :none))))))
2039 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2040 "Helper for `yas-define-menu'."
2041 (dolist (e (reverse menu))
2042 (cond ((eq (first e) 'yas-item)
2043 (let ((template (or (gethash (second e) uuidhash)
2044 (yas--populate-template (puthash (second e)
2045 (yas--make-blank-template)
2048 :perm-group group-list
2049 :uuid (second e)))))
2050 (define-key menu-keymap (vector (gensym))
2051 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2052 ((eq (first e) 'yas-submenu)
2053 (let ((subkeymap (make-sparse-keymap)))
2054 (define-key menu-keymap (vector (gensym))
2055 `(menu-item ,(second e) ,subkeymap))
2056 (yas--define-menu-1 table
2060 (append group-list (list (second e))))))
2061 ((eq (first e) 'yas-separator)
2062 (define-key menu-keymap (vector (gensym))
2063 '(menu-item "----")))
2065 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2067 (defun yas--define (mode key template &optional name condition group)
2068 "Define a snippet. Expanding KEY into TEMPLATE.
2070 NAME is a description to this template. Also update the menu if
2071 `yas-use-menu' is t. CONDITION is the condition attached to
2072 this snippet. If you attach a condition to a snippet, then it
2073 will only be expanded when the condition evaluated to non-nil."
2074 (yas-define-snippets mode
2075 (list (list key template name condition group))))
2077 (defun yas-hippie-try-expand (first-time?)
2078 "Integrate with hippie expand.
2080 Just put this function in `hippie-expand-try-functions-list'."
2081 (when yas-minor-mode
2082 (if (not first-time?)
2083 (let ((yas-fallback-behavior 'return-nil))
2089 ;;; Apropos condition-cache:
2094 (defvar yas--condition-cache-timestamp nil)
2095 (defmacro yas-define-condition-cache (func doc &rest body)
2096 "Define a function FUNC with doc DOC and body BODY.
2097 BODY is executed at most once every snippet expansion attempt, to check
2098 expansion conditions.
2100 It doesn't make any sense to call FUNC programatically."
2101 `(defun ,func () ,(if (and doc
2104 "\n\nFor use in snippets' conditions. Within each
2105 snippet-expansion routine like `yas-expand', computes actual
2106 value for the first time then always returns a cached value.")
2107 (setq body (cons doc body))
2109 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2110 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2111 (cdr timestamp-and-value)
2112 (let ((new-value (progn
2115 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2118 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2119 (defun yas-expand-from-trigger-key (&optional field)
2120 "Expand a snippet before point.
2122 If no snippet expansion is possible, fall back to the behaviour
2123 defined in `yas-fallback-behavior'.
2125 Optional argument FIELD is for non-interactive use and is an
2126 object satisfying `yas--field-p' to restrict the expansion to."
2128 (setq yas--condition-cache-timestamp (current-time))
2129 (let (templates-and-pos)
2130 (unless (and yas-expand-only-for-last-commands
2131 (not (member last-command yas-expand-only-for-last-commands)))
2132 (setq templates-and-pos (if field
2134 (narrow-to-region (yas--field-start field)
2135 (yas--field-end field))
2137 (yas--current-key))))
2138 (if (and templates-and-pos
2139 (first templates-and-pos))
2140 (yas--expand-or-prompt-for-template (first templates-and-pos)
2141 (second templates-and-pos)
2142 (third templates-and-pos))
2145 (defun yas-expand-from-keymap ()
2146 "Directly expand some snippets, searching `yas--direct-keymaps'.
2148 If expansion fails, execute the previous binding for this key"
2150 (setq yas--condition-cache-timestamp (current-time))
2151 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2152 (length (this-command-keys))
2154 (templates (mapcan #'(lambda (table)
2155 (yas--fetch table vec))
2156 (yas--get-snippet-tables))))
2158 (yas--expand-or-prompt-for-template templates)
2159 (let ((yas-fallback-behavior 'call-other-command))
2162 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2163 "Expand one of TEMPLATES from START to END.
2165 Prompt the user if TEMPLATES has more than one element, else
2166 expand immediately. Common gateway for
2167 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2168 (let ((yas--current-template (or (and (rest templates) ;; more than one
2169 (yas--prompt-for-template (mapcar #'cdr templates)))
2171 (when yas--current-template
2172 (yas-expand-snippet (yas--template-content yas--current-template)
2175 (yas--template-expand-env yas--current-template)))))
2177 ;; Apropos the trigger key and the fallback binding:
2179 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2180 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2181 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2182 ;; improve this explanation.
2184 (defun yas--fallback ()
2185 "Fallback after expansion has failed.
2187 Common gateway for `yas-expand-from-trigger-key' and
2188 `yas-expand-from-keymap'."
2189 (cond ((eq yas-fallback-behavior 'return-nil)
2192 ((eq yas-fallback-behavior 'call-other-command)
2193 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2194 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2195 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2196 (setq this-original-command beyond-yasnippet)
2197 (when beyond-yasnippet
2198 (call-interactively beyond-yasnippet))))
2199 ((and (listp yas-fallback-behavior)
2200 (cdr yas-fallback-behavior)
2201 (eq 'apply (car yas-fallback-behavior)))
2202 (if (cddr yas-fallback-behavior)
2203 (apply (cadr yas-fallback-behavior)
2204 (cddr yas-fallback-behavior))
2205 (when (commandp (cadr yas-fallback-behavior))
2206 (setq this-command (cadr yas-fallback-behavior))
2207 (call-interactively (cadr yas-fallback-behavior)))))
2209 ;; also return nil if all the other fallbacks have failed
2212 (defun yas--keybinding-beyond-yasnippet ()
2214 (let* ((yas-minor-mode nil)
2215 (yas--direct-keymaps nil)
2216 (keys (this-single-command-keys)))
2217 (or (key-binding keys t)
2218 (key-binding (yas--fallback-translate-input keys) t))))
2220 (defun yas--fallback-translate-input (keys)
2221 "Emulate `read-key-sequence', at least what I think it does.
2223 Keys should be an untranslated key vector. Returns a translated
2224 vector of keys. FIXME not thoroughly tested."
2227 (while (< i (length keys))
2229 (translated local-function-key-map))
2230 (while (and (< j (length keys))
2232 (keymapp translated))
2233 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2235 (setq retval (vconcat retval (cond ((symbolp translated)
2237 ((vectorp translated)
2240 (substring keys i j)))))
2245 ;;; Utils for snippet development:
2247 (defun yas--all-templates (tables)
2248 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2250 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2251 `yas-buffer-local-condition'"
2252 (when yas-choose-tables-first
2253 (setq tables (list (yas--prompt-for-table tables))))
2255 (if yas-choose-keys-first
2256 (let ((key (yas--prompt-for-keys
2257 (mapcan #'yas--table-all-keys tables))))
2259 (mapcan #'(lambda (table)
2260 (yas--fetch table key))
2262 (remove-duplicates (mapcan #'yas--table-templates tables)
2265 (defun yas-insert-snippet (&optional no-condition)
2266 "Choose a snippet to expand, pop-up a list of choices according
2267 to `yas-prompt-functions'.
2269 With prefix argument NO-CONDITION, bypass filtering of snippets
2272 (setq yas--condition-cache-timestamp (current-time))
2273 (let* ((yas-buffer-local-condition (or (and no-condition
2275 yas-buffer-local-condition))
2276 (templates (yas--all-templates (yas--get-snippet-tables)))
2277 (yas--current-template (and templates
2278 (or (and (rest templates) ;; more than one template for same key
2279 (yas--prompt-for-template templates))
2281 (where (if (region-active-p)
2282 (cons (region-beginning) (region-end))
2283 (cons (point) (point)))))
2284 (if yas--current-template
2285 (yas-expand-snippet (yas--template-content yas--current-template)
2288 (yas--template-expand-env yas--current-template))
2289 (yas--message 3 "No snippets can be inserted here!"))))
2291 (defun yas-visit-snippet-file ()
2292 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2294 Only success if selected snippet was loaded from a file. Put the
2295 visited file in `snippet-mode'."
2297 (let* ((yas-buffer-local-condition 'always)
2298 (templates (yas--all-templates (yas--get-snippet-tables)))
2299 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2300 (template (and templates
2301 (or (yas--prompt-for-template templates
2302 "Choose a snippet template to edit: ")
2306 (yas--visit-snippet-file-1 template)
2307 (message "No snippets tables active!"))))
2309 (defun yas--visit-snippet-file-1 (template)
2310 "Helper for `yas-visit-snippet-file'."
2311 (let ((file (yas--template-file template)))
2312 (cond ((and file (file-readable-p file))
2313 (find-file-other-window file)
2315 (set (make-local-variable 'yas--editing-template) template))
2317 (message "Original file %s no longer exists!" file))
2319 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2320 (let ((type 'snippet))
2321 (when (listp (yas--template-content template))
2322 (insert (format "# type: command\n"))
2323 (setq type 'command))
2324 (insert (format "# key: %s\n" (yas--template-key template)))
2325 (insert (format "# name: %s\n" (yas--template-name template)))
2326 (when (yas--template-keybinding template)
2327 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2328 (when (yas--template-expand-env template)
2329 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2330 (when (yas--template-condition template)
2331 (insert (format "# condition: %s\n" (yas--template-condition template))))
2333 (insert (if (eq type 'command)
2334 (pp-to-string (yas--template-content template))
2335 (yas--template-content template))))
2337 (set (make-local-variable 'yas--editing-template) template)))))
2339 (defun yas--guess-snippet-directories-1 (table)
2340 "Guess possible snippet subdirectories for TABLE."
2341 (cons (yas--table-name table)
2342 (mapcan #'(lambda (parent)
2343 (yas--guess-snippet-directories-1
2345 (yas--table-parents table))))
2347 (defun yas--guess-snippet-directories (&optional table)
2348 "Try to guess suitable directories based on the current active
2349 tables (or optional TABLE).
2351 Returns a list of elements (TABLE . DIRS) where TABLE is a
2352 `yas--table' object and DIRS is a list of all possible directories
2353 where snippets of table might exist."
2354 (let ((main-dir (replace-regexp-in-string
2356 (or (first (or (yas-snippet-dirs)
2357 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2358 (tables (or (and table
2360 (yas--get-snippet-tables))))
2361 ;; HACK! the snippet table created here is actually registered!
2363 (unless (or table (gethash major-mode yas--tables))
2364 (push (yas--table-get-create major-mode)
2367 (mapcar #'(lambda (table)
2369 (mapcar #'(lambda (subdir)
2370 (concat main-dir "/" subdir))
2371 (yas--guess-snippet-directories-1 table))))
2374 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2375 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2376 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2377 (let ((candidate (first (cdr table-and-dirs))))
2378 (unless (file-writable-p (file-name-directory candidate))
2379 (error (yas--format "%s is not writable." candidate)))
2380 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2382 (if (gethash (yas--table-mode (car table-and-dirs))
2386 (or main-table-string
2388 (yas--table-name (car table-and-dirs))))
2390 (make-directory candidate 'also-make-parents)
2391 ;; create the .yas-parents file here...
2394 (defun yas-new-snippet (&optional no-template)
2395 "Pops a new buffer for writing a snippet.
2397 Expands a snippet-writing snippet, unless the optional prefix arg
2398 NO-TEMPLATE is non-nil."
2400 (let ((guessed-directories (yas--guess-snippet-directories)))
2402 (switch-to-buffer "*new snippet*")
2404 (kill-all-local-variables)
2407 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2408 (yas--table-mode (car d)))
2409 guessed-directories))
2410 (if (and (not no-template) yas-new-snippet-default)
2411 (yas-expand-snippet yas-new-snippet-default))))
2413 (defun yas--compute-major-mode-and-parents (file)
2414 "Given FILE, find the nearest snippet directory for a given mode.
2416 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2417 representing one or more of the mode's parents.
2419 Note that MODE-SYM need not be the symbol of a real major mode,
2420 neither do the elements of PARENTS."
2421 (let* ((file-dir (and file
2422 (directory-file-name (or (some #'(lambda (special)
2423 (locate-dominating-file file special))
2427 (directory-file-name (file-name-directory file))))))
2428 (parents-file-name (concat file-dir "/.yas-parents"))
2429 (major-mode-name (and file-dir
2430 (file-name-nondirectory file-dir)))
2431 (major-mode-sym (or (and major-mode-name
2432 (intern major-mode-name))))
2433 (parents (when (file-readable-p parents-file-name)
2437 (insert-file-contents parents-file-name)
2438 (buffer-substring-no-properties (point-min)
2440 (when major-mode-sym
2441 (cons major-mode-sym (remove major-mode-sym parents)))))
2443 (defvar yas--editing-template nil
2444 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2446 (defvar yas--current-template nil
2447 "Holds the current template being expanded into a snippet.")
2449 (defvar yas--guessed-modes nil
2450 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2452 (defun yas--read-table ()
2453 "Ask user for a snippet table, help with some guessing."
2454 (let ((prompt (if (and (featurep 'ido)
2456 'ido-completing-read 'completing-read)))
2457 (unless yas--guessed-modes
2458 (set (make-local-variable 'yas--guessed-modes)
2459 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2461 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2462 (if yas--guessed-modes
2463 (first yas--guessed-modes)
2465 (mapcar #'symbol-name yas--guessed-modes)
2470 (if (first yas--guessed-modes)
2471 (symbol-name (first yas--guessed-modes)))))))
2473 (defun yas-load-snippet-buffer (table &optional interactive)
2474 "Parse and load current buffer's snippet definition into TABLE.
2476 TABLE is a symbol naming a passed to `yas--table-get-create'.
2478 When called interactively, prompt for the table name."
2479 (interactive (list (yas--read-table) t))
2481 ;; We have `yas--editing-template', this buffer's content comes from a
2482 ;; template which is already loaded and neatly positioned,...
2484 (yas--editing-template
2485 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2486 (yas--template-table yas--editing-template)))
2487 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2488 ;; value from `yas--compute-major-mode-and-parents'
2491 (unless yas--guessed-modes
2492 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2493 (let* ((table (yas--table-get-create table)))
2494 (set (make-local-variable 'yas--editing-template)
2495 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2498 (yas--message 3 "Snippet \"%s\" loaded for %s."
2499 (yas--template-name yas--editing-template)
2500 (yas--table-name (yas--template-table yas--editing-template)))))
2502 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2503 "Load the snippet with `yas-load-snippet-buffer', possibly
2504 save, then `quit-window' if saved.
2506 If the snippet is new, ask the user whether (and where) to save
2507 it. If the snippet already has a file, just save it.
2509 The prefix argument KILL is passed to `quit-window'.
2511 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2512 and `kill-buffer' instead."
2513 (interactive (list (yas--read-table) current-prefix-arg))
2514 (yas-load-snippet-buffer table t)
2516 ;; Only offer to save this if it looks like a library or new
2517 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2518 ;; which is not the first, or from an unwritable file)
2520 (not (yas--template-file yas--editing-template))
2521 (not (file-writable-p (yas--template-file yas--editing-template)))
2522 (and (listp yas-snippet-dirs)
2523 (second yas-snippet-dirs)
2524 (not (string-match (expand-file-name (first yas-snippet-dirs))
2525 (yas--template-file yas--editing-template)))))
2526 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2527 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2529 (yas--make-directory-maybe option))))
2531 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2532 (file-name-nondirectory (yas--template-file yas--editing-template)))
2533 (yas--template-name yas--editing-template))))
2534 (write-file (concat chosen "/"
2535 (read-from-minibuffer (format "File name to create in %s? " chosen)
2536 default-file-name)))
2537 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2538 (when buffer-file-name
2540 (quit-window kill)))
2542 (defun yas-tryout-snippet (&optional debug)
2543 "Test current buffer's snippet template in other buffer."
2545 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2546 (parsed (yas--parse-template))
2547 (test-mode (or (and (car major-mode-and-parent)
2548 (fboundp (car major-mode-and-parent))
2549 (car major-mode-and-parent))
2550 (first yas--guessed-modes)
2551 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2552 (yas--current-template
2555 (yas--populate-template (yas--make-blank-template)
2556 :table nil ;; no tables for ephemeral snippets
2558 :content (second parsed)
2559 :name (third parsed)
2560 :expand-env (sixth parsed)))))
2561 (cond (yas--current-template
2562 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2563 (kill-buffer (get-buffer-create buffer-name))
2564 (switch-to-buffer (get-buffer-create buffer-name))
2565 (setq buffer-undo-list nil)
2566 (condition-case nil (funcall test-mode) (error nil))
2568 (setq buffer-read-only nil)
2569 (yas-expand-snippet (yas--template-content yas--current-template)
2572 (yas--template-expand-env yas--current-template))
2574 (require 'yasnippet-debug nil t))
2575 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2577 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2579 (defun yas-active-keys ()
2580 "Return all active trigger keys for current buffer and point."
2582 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2585 (defun yas--template-fine-group (template)
2586 (car (last (or (yas--template-group template)
2587 (yas--template-perm-group template)))))
2589 (defun yas-describe-tables (&optional choose)
2590 "Display snippets for each table."
2592 (let* ((by-name-hash (and choose
2593 (y-or-n-p "Show by namehash? ")))
2594 (buffer (get-buffer-create "*YASnippet tables*"))
2595 (active-tables (yas--get-snippet-tables))
2596 (remain-tables (let ((all))
2597 (maphash #'(lambda (_k v)
2598 (unless (find v active-tables)
2602 (table-lists (list active-tables remain-tables))
2603 (original-buffer (current-buffer))
2605 (yas--condition-cache-timestamp (current-time)))
2606 (with-current-buffer buffer
2607 (setq buffer-read-only nil)
2609 (cond ((not by-name-hash)
2610 (insert "YASnippet tables: \n")
2611 (while (and table-lists
2613 (dolist (table (car table-lists))
2614 (yas--describe-pretty-table table original-buffer))
2615 (setq table-lists (cdr table-lists))
2617 (yas--create-snippet-xrefs)
2618 (display-buffer buffer)
2619 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2620 (yas--create-snippet-xrefs)
2624 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2625 (dolist (table (append active-tables remain-tables))
2626 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2628 (maphash #'(lambda (k _v)
2630 (yas--table-hash table))
2632 (insert (format " key %s maps snippets: %s\n" key
2634 (maphash #'(lambda (k _v)
2636 (gethash key (yas--table-hash table)))
2639 (setq buffer-read-only t))
2640 (display-buffer buffer)))
2642 (defun yas--describe-pretty-table (table &optional original-buffer)
2643 (insert (format "\nSnippet table `%s'"
2644 (yas--table-name table)))
2645 (if (yas--table-parents table)
2646 (insert (format " parents: %s\n"
2647 (mapcar #'yas--table-name
2648 (yas--table-parents table))))
2650 (insert (make-string 100 ?-) "\n")
2651 (insert "group state name key binding\n")
2652 (let ((groups-hash (make-hash-table :test #'equal)))
2653 (maphash #'(lambda (_k v)
2654 (let ((group (or (yas--template-fine-group v)
2656 (when (yas--template-name v)
2658 (cons v (gethash group groups-hash))
2660 (yas--table-uuidhash table))
2662 #'(lambda (group templates)
2663 (setq group (truncate-string-to-width group 25 0 ? "..."))
2664 (insert (make-string 100 ?-) "\n")
2665 (dolist (p templates)
2666 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2670 (setq group (make-string (length group) ? ))))
2671 (condition-string (let ((condition (yas--template-condition p)))
2674 (with-current-buffer original-buffer
2675 (if (yas--eval-condition condition)
2680 (insert condition-string " ")
2682 (if (string-match "\\.\\.\\.$" name)
2686 (insert (truncate-string-to-width (or (yas--template-key p) "")
2688 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2695 ;;; User convenience functions, for using in snippet definitions
2697 (defvar yas-modified-p nil
2698 "Non-nil if field has been modified by user or transformation.")
2700 (defvar yas-moving-away-p nil
2701 "Non-nil if user is about to exit field.")
2703 (defvar yas-text nil
2704 "Contains current field text.")
2706 (defun yas-substr (str pattern &optional subexp)
2707 "Search PATTERN in STR and return SUBEXPth match.
2709 If found, the content of subexp group SUBEXP (default 0) is
2710 returned, or else the original STR will be returned."
2711 (let ((grp (or subexp 0)))
2713 (if (string-match pattern str)
2714 (match-string-no-properties grp str)
2717 (defun yas-choose-value (&rest possibilities)
2718 "Prompt for a string in POSSIBILITIES and return it.
2720 The last element of POSSIBILITIES may be a list of strings."
2721 (unless (or yas-moving-away-p
2723 (let* ((last-link (last possibilities))
2724 (last-elem (car last-link)))
2725 (when (listp last-elem)
2726 (setcar last-link (car last-elem))
2727 (setcdr last-link (cdr last-elem))))
2728 (some #'(lambda (fn)
2729 (funcall fn "Choose: " possibilities))
2730 yas-prompt-functions)))
2732 (defun yas-key-to-value (alist)
2733 (unless (or yas-moving-away-p
2735 (let ((key (read-key-sequence "")))
2737 (or (cdr (find key alist :key #'car :test #'string=))
2740 (defun yas-throw (text)
2741 "Throw a yas--exception with TEXT as the reason."
2742 (throw 'yas--exception (cons 'yas--exception text)))
2744 (defun yas-verify-value (possibilities)
2745 "Verify that the current field value is in POSSIBILITIES.
2747 Otherwise throw exception."
2748 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2749 (yas-throw (yas--format "Field only allows %s" possibilities))))
2751 (defun yas-field-value (number)
2752 "Get the string for field with NUMBER.
2754 Use this in primary and mirror transformations to tget."
2755 (let* ((snippet (car (yas--snippets-at-point)))
2757 (yas--snippet-find-field snippet number))))
2759 (yas--field-text-for-display field))))
2762 "Return `yas-text' if that exists and is non-empty, else nil."
2764 (not (string= "" yas-text)))
2767 (defun yas-selected-text ()
2768 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2769 (if (and yas-selected-text
2770 (not (string= "" yas-selected-text)))
2773 (defun yas--get-field-once (number &optional transform-fn)
2774 (unless yas-modified-p
2776 (funcall transform-fn (yas-field-value number))
2777 (yas-field-value number))))
2779 (defun yas-default-from-field (number)
2780 (unless yas-modified-p
2781 (yas-field-value number)))
2783 (defun yas-inside-string ()
2784 "Return non-nil if the point is inside a string according to font-lock."
2785 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2787 (defun yas-unimplemented (&optional missing-feature)
2788 (if yas--current-template
2789 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2792 (yas--visit-snippet-file-1 yas--current-template))
2793 (message "No implementation. Missing %s" (or missing-feature "something"))))
2796 ;;; Snippet expansion and field management
2798 (defvar yas--active-field-overlay nil
2799 "Overlays the currently active field.")
2801 (defvar yas--field-protection-overlays nil
2802 "Two overlays protect the current active field.")
2804 (defvar yas-selected-text nil
2805 "The selected region deleted on the last snippet expansion.")
2807 (defvar yas--start-column nil
2808 "The column where the snippet expansion started.")
2810 (make-variable-buffer-local 'yas--active-field-overlay)
2811 (make-variable-buffer-local 'yas--field-protection-overlays)
2812 (put 'yas--active-field-overlay 'permanent-local t)
2813 (put 'yas--field-protection-overlays 'permanent-local t)
2815 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2821 (id (yas--snippet-next-id) :read-only t)
2822 (control-overlay nil)
2824 ;; stacked expansion: the `previous-active-field' slot saves the
2825 ;; active field where the child expansion took place
2826 previous-active-field
2829 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2832 NUMBER is the field number.
2833 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2834 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2835 MIRRORS is a list of `yas--mirror's
2836 TRANSFORM is a lisp form.
2837 MODIFIED-P is a boolean set to true once user inputs text.
2838 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2849 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2852 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2853 TRANSFORM is a lisp form.
2854 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2855 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2856 DEPTH is a count of how many nested mirrors can affect this mirror"
2863 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2867 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2868 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2870 If there is no transform for ht field, return nil.
2872 If there is a transform but it returns nil, return the empty
2873 string iff EMPTY-ON-NIL-P is true."
2874 (let* ((yas-text (yas--field-text-for-display field))
2875 (yas-modified-p (yas--field-modified-p field))
2876 (yas-moving-away-p nil)
2877 (transform (if (yas--mirror-p field-or-mirror)
2878 (yas--mirror-transform field-or-mirror)
2879 (yas--field-transform field-or-mirror)))
2880 (start-point (if (yas--mirror-p field-or-mirror)
2881 (yas--mirror-start field-or-mirror)
2882 (yas--field-start field-or-mirror)))
2883 (transformed (and transform
2885 (goto-char start-point)
2886 (let ((ret (yas--eval-lisp transform)))
2887 (or ret (and empty-on-nil-p "")))))))
2890 (defsubst yas--replace-all (from to &optional text)
2891 "Replace all occurrences from FROM to TO.
2893 With optional string TEXT do it in that string."
2895 (replace-regexp-in-string (regexp-quote from) to text t t)
2896 (goto-char (point-min))
2897 (while (search-forward from nil t)
2898 (replace-match to t t text))))
2900 (defun yas--snippet-find-field (snippet number)
2901 (find-if #'(lambda (field)
2902 (eq number (yas--field-number field)))
2903 (yas--snippet-fields snippet)))
2905 (defun yas--snippet-sort-fields (snippet)
2906 "Sort the fields of SNIPPET in navigation order."
2907 (setf (yas--snippet-fields snippet)
2908 (sort (yas--snippet-fields snippet)
2909 #'yas--snippet-field-compare)))
2911 (defun yas--snippet-field-compare (field1 field2)
2912 "Compare FIELD1 and FIELD2.
2914 The field with a number is sorted first. If they both have a
2915 number, compare through the number. If neither have, compare
2916 through the field's start point"
2917 (let ((n1 (yas--field-number field1))
2918 (n2 (yas--field-number field2)))
2921 (or (zerop n2) (and (not (zerop n1))
2926 (< (yas--field-start field1)
2927 (yas--field-start field2))))))
2929 (defun yas--field-probably-deleted-p (snippet field)
2930 "Guess if SNIPPET's FIELD should be skipped."
2932 ;; field must be zero length
2934 (zerop (- (yas--field-start field) (yas--field-end field)))
2937 ;; 1) is a nested field and it's been modified
2939 (and (yas--field-parent-field field)
2940 (yas--field-modified-p field))
2941 ;; 2) ends just before the snippet end
2943 (and (eq field (car (last (yas--snippet-fields snippet))))
2944 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2945 ;; the field numbered 0, just before the exit marker, should
2948 (not (zerop (yas--field-number field)))))
2950 (defun yas--snippets-at-point (&optional all-snippets)
2951 "Return a sorted list of snippets at point.
2953 The most recently-inserted snippets are returned first."
2955 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2956 (overlay-get ov 'yas--snippet))
2958 (overlays-in (point-min) (point-max))
2959 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2961 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
2963 (defun yas-next-field-or-maybe-expand ()
2964 "Try to expand a snippet at a key before point.
2966 Otherwise delegate to `yas-next-field'."
2968 (if yas-triggers-in-field
2969 (let ((yas-fallback-behavior 'return-nil)
2970 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
2972 (unless (yas-expand-from-trigger-key active-field)
2976 (defun yas-next-field (&optional arg)
2977 "Navigate to the ARGth next field.
2979 If there's none, exit the snippet."
2983 (snippet (first (yas--snippets-at-point)))
2984 (active-field (overlay-get yas--active-field-overlay 'yas--field))
2985 (live-fields (remove-if #'(lambda (field)
2986 (and (not (eq field active-field))
2987 (yas--field-probably-deleted-p snippet field)))
2988 (yas--snippet-fields snippet)))
2989 (active-field-pos (position active-field live-fields))
2990 (target-pos (and active-field-pos (+ arg active-field-pos)))
2991 (target-field (and target-pos (nth target-pos live-fields))))
2992 ;; First check if we're moving out of a field with a transform
2994 (when (and active-field
2995 (yas--field-transform active-field))
2996 (let* ((yas-moving-away-p t)
2997 (yas-text (yas--field-text-for-display active-field))
2998 (yas-modified-p (yas--field-modified-p active-field)))
2999 ;; primary field transform: exit call to field-transform
3000 (yas--eval-lisp (yas--field-transform active-field))))
3001 ;; Now actually move...
3002 (cond ((and target-pos (>= target-pos (length live-fields)))
3003 (yas-exit-snippet snippet))
3005 (yas--move-to-field snippet target-field))
3009 (defun yas--place-overlays (snippet field)
3010 "Correctly place overlays for SNIPPET's FIELD."
3011 (yas--make-move-field-protection-overlays snippet field)
3012 (yas--make-move-active-field-overlay snippet field))
3014 (defun yas--move-to-field (snippet field)
3015 "Update SNIPPET to move to field FIELD.
3017 Also create some protection overlays"
3018 (goto-char (yas--field-start field))
3019 (yas--place-overlays snippet field)
3020 (overlay-put yas--active-field-overlay 'yas--field field)
3021 (let ((number (yas--field-number field)))
3022 ;; check for the special ${0: ...} field
3023 (if (and number (zerop number))
3025 (set-mark (yas--field-end field))
3026 (setf (yas--snippet-force-exit snippet)
3027 (or (yas--field-transform field)
3029 ;; make this field active
3030 (setf (yas--snippet-active-field snippet) field)
3031 ;; primary field transform: first call to snippet transform
3032 (unless (yas--field-modified-p field)
3033 (if (yas--field-update-display field)
3034 (yas--update-mirrors snippet)
3035 (setf (yas--field-modified-p field) nil))))))
3037 (defun yas-prev-field ()
3038 "Navigate to prev field. If there's none, exit the snippet."
3040 (yas-next-field -1))
3042 (defun yas-abort-snippet (&optional snippet)
3044 (let ((snippet (or snippet
3045 (car (yas--snippets-at-point)))))
3047 (setf (yas--snippet-force-exit snippet) t))))
3049 (defun yas-exit-snippet (snippet)
3050 "Goto exit-marker of SNIPPET."
3051 (interactive (list (first (yas--snippets-at-point))))
3053 (setf (yas--snippet-force-exit snippet) t)
3054 (goto-char (if (yas--snippet-exit snippet)
3055 (yas--exit-marker (yas--snippet-exit snippet))
3056 (overlay-end (yas--snippet-control-overlay snippet))))))
3058 (defun yas-exit-all-snippets ()
3059 "Exit all snippets."
3061 (mapc #'(lambda (snippet)
3062 (yas-exit-snippet snippet)
3063 (yas--check-commit-snippet))
3064 (yas--snippets-at-point 'all-snippets)))
3067 ;;; Some low level snippet-routines:
3069 (defvar yas--inhibit-overlay-hooks nil
3070 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3072 (defmacro yas--inhibit-overlay-hooks (&rest body)
3073 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3074 (declare (indent 0))
3075 `(let ((yas--inhibit-overlay-hooks t))
3078 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3079 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3081 (defun yas--commit-snippet (snippet)
3082 "Commit SNIPPET, but leave point as it is.
3084 This renders the snippet as ordinary text."
3086 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3088 ;; Save the end of the moribund snippet in case we need to revive it
3089 ;; its original expansion.
3091 (when (and control-overlay
3092 (overlay-buffer control-overlay))
3093 (setq yas-snippet-beg (overlay-start control-overlay))
3094 (setq yas-snippet-end (overlay-end control-overlay))
3095 (delete-overlay control-overlay))
3097 (yas--inhibit-overlay-hooks
3098 (when yas--active-field-overlay
3099 (delete-overlay yas--active-field-overlay))
3100 (when yas--field-protection-overlays
3101 (mapc #'delete-overlay yas--field-protection-overlays)))
3103 ;; stacked expansion: if the original expansion took place from a
3104 ;; field, make sure we advance it here at least to
3105 ;; `yas-snippet-end'...
3107 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3108 (when (and yas-snippet-end previous-field)
3109 (yas--advance-end-maybe previous-field yas-snippet-end)))
3111 ;; Convert all markers to points,
3113 (yas--markers-to-points snippet)
3115 ;; Take care of snippet revival
3117 (if yas-snippet-revival
3118 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3120 ;; Dismember the snippet... this is useful if we get called
3121 ;; again from `yas--take-care-of-redo'....
3122 (setf (yas--snippet-fields snippet) nil)))
3124 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3126 (defun yas--safely-run-hooks (hook-var)
3127 (condition-case error
3128 (run-hooks hook-var)
3130 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3133 (defun yas--check-commit-snippet ()
3134 "Check if point exited the currently active field of the snippet.
3136 If so cleans up the whole snippet up."
3137 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3138 (snippets-left snippets)
3139 (snippet-exit-transform))
3140 (dolist (snippet snippets)
3141 (let ((active-field (yas--snippet-active-field snippet)))
3142 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3143 (cond ((or snippet-exit-transform
3144 (not (and active-field (yas--field-contains-point-p active-field))))
3145 (setq snippets-left (delete snippet snippets-left))
3146 (setf (yas--snippet-force-exit snippet) nil)
3147 (yas--commit-snippet snippet))
3149 (or (not yas--active-field-overlay)
3150 (not (overlay-buffer yas--active-field-overlay))))
3152 ;; stacked expansion: this case is mainly for recent
3153 ;; snippet exits that place us back int the field of
3157 (yas--move-to-field snippet active-field)
3158 (yas--update-mirrors snippet)))
3161 (unless (or (null snippets) snippets-left)
3162 (if snippet-exit-transform
3163 (yas--eval-lisp-no-saves snippet-exit-transform))
3164 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3166 ;; Apropos markers-to-points:
3168 ;; This was found useful for performance reasons, so that an
3169 ;; excessive number of live markers aren't kept around in the
3170 ;; `buffer-undo-list'. However, in `markers-to-points', the
3171 ;; set-to-nil markers can't simply be discarded and replaced with
3172 ;; fresh ones in `points-to-markers'. The original marker that was
3173 ;; just set to nil has to be reused.
3175 ;; This shouldn't bring horrible problems with undo/redo, but it
3178 (defun yas--markers-to-points (snippet)
3179 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3180 where POINT is the original position of the marker and MARKER is
3181 the original marker object with the position set to nil."
3182 (dolist (field (yas--snippet-fields snippet))
3183 (let ((start (marker-position (yas--field-start field)))
3184 (end (marker-position (yas--field-end field))))
3185 (set-marker (yas--field-start field) nil)
3186 (set-marker (yas--field-end field) nil)
3187 (setf (yas--field-start field) (cons start (yas--field-start field)))
3188 (setf (yas--field-end field) (cons end (yas--field-end field))))
3189 (dolist (mirror (yas--field-mirrors field))
3190 (let ((start (marker-position (yas--mirror-start mirror)))
3191 (end (marker-position (yas--mirror-end mirror))))
3192 (set-marker (yas--mirror-start mirror) nil)
3193 (set-marker (yas--mirror-end mirror) nil)
3194 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3195 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3196 (let ((snippet-exit (yas--snippet-exit snippet)))
3198 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3199 (set-marker (yas--exit-marker snippet-exit) nil)
3200 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3202 (defun yas--points-to-markers (snippet)
3203 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3205 This is done by setting MARKER to POINT with `set-marker'."
3206 (dolist (field (yas--snippet-fields snippet))
3207 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3208 (car (yas--field-start field))))
3209 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3210 (car (yas--field-end field))))
3211 (dolist (mirror (yas--field-mirrors field))
3212 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3213 (car (yas--mirror-start mirror))))
3214 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3215 (car (yas--mirror-end mirror))))))
3216 (let ((snippet-exit (yas--snippet-exit snippet)))
3218 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3219 (car (yas--exit-marker snippet-exit)))))))
3221 (defun yas--field-contains-point-p (field &optional point)
3222 (let ((point (or point
3224 (and (>= point (yas--field-start field))
3225 (<= point (yas--field-end field)))))
3227 (defun yas--field-text-for-display (field)
3228 "Return the propertized display text for field FIELD."
3229 (buffer-substring (yas--field-start field) (yas--field-end field)))
3231 (defun yas--undo-in-progress ()
3232 "True if some kind of undo is in progress."
3233 (or undo-in-progress
3234 (eq this-command 'undo)
3235 (eq this-command 'redo)))
3237 (defun yas--make-control-overlay (snippet start end)
3238 "Create the control overlay that surrounds the snippet and
3240 (let ((overlay (make-overlay start
3245 (overlay-put overlay 'keymap yas-keymap)
3246 (overlay-put overlay 'priority 100)
3247 (overlay-put overlay 'yas--snippet snippet)
3250 (defun yas-skip-and-clear-or-delete-char (&optional field)
3251 "Clears unmodified field if at field start, skips to next tab.
3253 Otherwise deletes a character normally by calling `delete-char'."
3255 (let ((field (or field
3256 (and yas--active-field-overlay
3257 (overlay-buffer yas--active-field-overlay)
3258 (overlay-get yas--active-field-overlay 'yas--field)))))
3260 (not (yas--field-modified-p field))
3261 (eq (point) (marker-position (yas--field-start field))))
3262 (yas--skip-and-clear field)
3265 (call-interactively 'delete-char)))))
3267 (defun yas--skip-and-clear (field)
3268 "Deletes the region of FIELD and sets it's modified state to t."
3269 ;; Just before skipping-and-clearing the field, mark its children
3270 ;; fields as modified, too. If the children have mirrors-in-fields
3271 ;; this prevents them from updating erroneously (we're skipping and
3274 (yas--mark-this-and-children-modified field)
3275 (delete-region (yas--field-start field) (yas--field-end field)))
3277 (defun yas--mark-this-and-children-modified (field)
3278 (setf (yas--field-modified-p field) t)
3279 (let ((fom (yas--field-next field)))
3281 (yas--fom-parent-field fom))
3282 (when (and (eq (yas--fom-parent-field fom) field)
3284 (yas--mark-this-and-children-modified fom))
3285 (setq fom (yas--fom-next fom)))))
3287 (defun yas--make-move-active-field-overlay (snippet field)
3288 "Place the active field overlay in SNIPPET's FIELD.
3290 Move the overlay, or create it if it does not exit."
3291 (if (and yas--active-field-overlay
3292 (overlay-buffer yas--active-field-overlay))
3293 (move-overlay yas--active-field-overlay
3294 (yas--field-start field)
3295 (yas--field-end field))
3296 (setq yas--active-field-overlay
3297 (make-overlay (yas--field-start field)
3298 (yas--field-end field)
3300 (overlay-put yas--active-field-overlay 'priority 100)
3301 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3302 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3303 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3304 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3305 '(yas--on-field-overlay-modification))
3306 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3307 '(yas--on-field-overlay-modification))))
3309 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3310 "Clears the field and updates mirrors, conditionally.
3312 Only clears the field if it hasn't been modified and it point it
3313 at field start. This hook doesn't do anything if an undo is in
3315 (unless (or yas--inhibit-overlay-hooks
3316 (yas--undo-in-progress))
3317 (let* ((field (overlay-get overlay 'yas--field))
3318 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3320 (yas--advance-end-maybe field (overlay-end overlay))
3322 (yas--field-update-display field))
3323 (yas--update-mirrors snippet))
3325 (when (and (not after?)
3326 (not (yas--field-modified-p field))
3327 (eq (point) (if (markerp (yas--field-start field))
3328 (marker-position (yas--field-start field))
3329 (yas--field-start field))))
3330 (yas--skip-and-clear field))
3331 (setf (yas--field-modified-p field) t))))))
3333 ;;; Apropos protection overlays:
3335 ;; These exist for nasty users who will try to delete parts of the
3336 ;; snippet outside the active field. Actual protection happens in
3337 ;; `yas--on-protection-overlay-modification'.
3339 ;; Currently this signals an error which inhibits the command. For
3340 ;; commands that move point (like `kill-line'), point is restored in
3341 ;; the `yas--post-command-handler' using a global
3342 ;; `yas--protection-violation' variable.
3344 ;; Alternatively, I've experimented with an implementation that
3345 ;; commits the snippet before actually calling `this-command'
3346 ;; interactively, and then signals an error, which is ignored. but
3347 ;; blocks all other million modification hooks. This presented some
3348 ;; problems with stacked expansion.
3350 (defun yas--make-move-field-protection-overlays (snippet field)
3351 "Place protection overlays surrounding SNIPPET's FIELD.
3353 Move the overlays, or create them if they do not exit."
3354 (let ((start (yas--field-start field))
3355 (end (yas--field-end field)))
3356 ;; First check if the (1+ end) is contained in the buffer,
3357 ;; otherwise we'll have to do a bit of cheating and silently
3358 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3359 ;; when using stacked expansion
3361 (when (< (buffer-size) end)
3363 (yas--inhibit-overlay-hooks
3364 (goto-char (point-max))
3366 ;; go on to normal overlay creation/moving
3368 (cond ((and yas--field-protection-overlays
3369 (every #'overlay-buffer yas--field-protection-overlays))
3370 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3371 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3373 (setq yas--field-protection-overlays
3374 (list (make-overlay (1- start) start nil t nil)
3375 (make-overlay end (1+ end) nil t nil)))
3376 (dolist (ov yas--field-protection-overlays)
3377 (overlay-put ov 'face 'yas--field-debug-face)
3378 (overlay-put ov 'yas--snippet snippet)
3379 ;; (overlay-put ov 'evaporate t)
3380 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3382 (defvar yas--protection-violation nil
3383 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3385 Functions in the `post-command-hook', for example
3386 `yas--post-command-handler' can check it and reset its value to
3387 nil. The variables value is the point where the violation
3390 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3391 "Signals a snippet violation, then issues error.
3393 The error should be ignored in `debug-ignored-errors'"
3394 (unless yas--inhibit-overlay-hooks
3395 (cond ((not (or after?
3396 (yas--undo-in-progress)))
3397 (setq yas--protection-violation (point))
3398 (error "Exit the snippet first!")))))
3400 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3403 ;;; Snippet expansion and "stacked" expansion:
3405 ;; Stacked expansion is when you try to expand a snippet when already
3406 ;; inside a snippet expansion.
3408 ;; The parent snippet does not run its fields modification hooks
3409 ;; (`yas--on-field-overlay-modification' and
3410 ;; `yas--on-protection-overlay-modification') while the child snippet
3411 ;; is active. This means, among other things, that the mirrors of the
3412 ;; parent snippet are not updated, this only happening when one exits
3413 ;; the child snippet.
3415 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3416 ;; bits of code in `yas-expand-snippet' and
3417 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3420 ;; This was thought to be safer in an undo/redo perspective, but
3421 ;; maybe the correct implementation is to make the globals
3422 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3423 ;; snippet-local and be active even while the child snippet is
3424 ;; running. This would mean a lot of overlay modification hooks
3425 ;; running, but if managed correctly (including overlay priorities)
3426 ;; they should account for all situations...
3428 (defun yas-expand-snippet (content &optional start end expand-env)
3429 "Expand snippet CONTENT at current point.
3431 Text between START and END will be deleted before inserting
3432 template. EXPAND-ENV is are let-style variable to value bindings
3433 considered when expanding the snippet."
3434 (run-hooks 'yas-before-expand-snippet-hook)
3437 (let* ((yas-selected-text (or yas-selected-text
3438 (and (region-active-p)
3439 (buffer-substring-no-properties (region-beginning)
3442 (and (region-active-p)
3446 (and (region-active-p)
3449 (to-delete (and start
3451 (buffer-substring-no-properties start end)))
3454 (setq yas--indent-original-column (current-column))
3455 ;; Delete the region to delete, this *does* get undo-recorded.
3457 (when (and to-delete
3459 (delete-region start end))
3461 (cond ((listp content)
3462 ;; x) This is a snippet-command
3464 (yas--eval-lisp-no-saves content))
3466 ;; x) This is a snippet-snippet :-)
3468 ;; Narrow the region down to the content, shoosh the
3469 ;; `buffer-undo-list', and create the snippet, the new
3470 ;; snippet updates its mirrors once, so we are left with
3471 ;; some plain text. The undo action for deleting this
3472 ;; plain text will get recorded at the end.
3474 ;; stacked expansion: also shoosh the overlay modification hooks
3475 (let ((buffer-undo-list t))
3476 ;; snippet creation might evaluate users elisp, which
3477 ;; might generate errors, so we have to be ready to catch
3478 ;; them mostly to make the undo information
3480 (setq yas--start-column (current-column))
3481 (yas--inhibit-overlay-hooks
3484 (eval `(let* ,expand-env
3486 (yas--snippet-create start (point))))
3488 (yas--snippet-create start (point))))))
3490 ;; stacked-expansion: This checks for stacked expansion, save the
3491 ;; `yas--previous-active-field' and advance its boundary.
3493 (let ((existing-field (and yas--active-field-overlay
3494 (overlay-buffer yas--active-field-overlay)
3495 (overlay-get yas--active-field-overlay 'yas--field))))
3496 (when existing-field
3497 (setf (yas--snippet-previous-active-field snippet) existing-field)
3498 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3500 ;; Exit the snippet immediately if no fields
3502 (unless (yas--snippet-fields snippet)
3503 (yas-exit-snippet snippet))
3505 ;; Push two undo actions: the deletion of the inserted contents of
3506 ;; the new snippet (without the "key") followed by an apply of
3507 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3509 ;; A small exception, if `yas-also-auto-indent-first-line'
3510 ;; is t and `yas--indent' decides to indent the line to a
3511 ;; point before the actual expansion point, undo would be
3512 ;; messed up. We call the early point "newstart"". case,
3513 ;; and attempt to fix undo.
3515 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3516 (end (overlay-end (yas--snippet-control-overlay snippet))))
3517 (when (< newstart start)
3518 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3519 (push (cons newstart end) buffer-undo-list)
3520 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3522 ;; Now, schedule a move to the first field
3524 (let ((first-field (car (yas--snippet-fields snippet))))
3526 (sit-for 0) ;; fix issue 125
3527 (yas--move-to-field snippet first-field)))
3528 (yas--message 3 "snippet expanded.")
3531 (defun yas--take-care-of-redo (_beg _end snippet)
3532 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3534 Meant to exit in the `buffer-undo-list'."
3535 ;; slightly optimize: this action is only needed for snippets with
3536 ;; at least one field
3537 (when (yas--snippet-fields snippet)
3538 (yas--commit-snippet snippet)))
3540 (defun yas--snippet-revive (beg end snippet)
3541 "Revives SNIPPET and creates a control overlay from BEG to END.
3543 BEG and END are, we hope, the original snippets boundaries.
3544 All the markers/points exiting existing inside SNIPPET should point
3545 to their correct locations *at the time the snippet is revived*.
3547 After revival, push the `yas--take-care-of-redo' in the
3549 ;; Reconvert all the points to markers
3551 (yas--points-to-markers snippet)
3552 ;; When at least one editable field existed in the zombie snippet,
3553 ;; try to revive the whole thing...
3555 (let ((target-field (or (yas--snippet-active-field snippet)
3556 (car (yas--snippet-fields snippet)))))
3558 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3559 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3561 (yas--move-to-field snippet target-field)
3563 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3564 buffer-undo-list))))
3566 (defun yas--snippet-create (begin end)
3567 "Create a snippet from a template inserted at BEGIN to END.
3569 Returns the newly created snippet."
3571 (narrow-to-region begin end)
3572 (let ((snippet (yas--make-snippet)))
3574 (yas--snippet-parse-create snippet)
3576 ;; Sort and link each field
3577 (yas--snippet-sort-fields snippet)
3579 ;; Create keymap overlay for snippet
3580 (setf (yas--snippet-control-overlay snippet)
3581 (yas--make-control-overlay snippet (point-min) (point-max)))
3584 (goto-char (point-max))
3589 ;;; Apropos adjacencies and "fom's":
3591 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3592 ;; recently expanded snippet, we might actually have many fields,
3593 ;; mirrors (and the snippet exit) in the very same position in the
3594 ;; buffer. Therefore we need to single-link the
3595 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3596 ;; according to their original positions in the buffer.
3598 ;; Then we have operation `yas--advance-end-maybe' and
3599 ;; `yas--advance-start-maybe', which conditionally push the starts and
3600 ;; ends of these foms down the chain.
3602 ;; This allows for like the printf with the magic ",":
3604 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3605 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3607 (defun yas--fom-start (fom)
3608 (cond ((yas--field-p fom)
3609 (yas--field-start fom))
3610 ((yas--mirror-p fom)
3611 (yas--mirror-start fom))
3613 (yas--exit-marker fom))))
3615 (defun yas--fom-end (fom)
3616 (cond ((yas--field-p fom)
3617 (yas--field-end fom))
3618 ((yas--mirror-p fom)
3619 (yas--mirror-end fom))
3621 (yas--exit-marker fom))))
3623 (defun yas--fom-next (fom)
3624 (cond ((yas--field-p fom)
3625 (yas--field-next fom))
3626 ((yas--mirror-p fom)
3627 (yas--mirror-next fom))
3629 (yas--exit-next fom))))
3631 (defun yas--fom-parent-field (fom)
3632 (cond ((yas--field-p fom)
3633 (yas--field-parent-field fom))
3634 ((yas--mirror-p fom)
3635 (yas--mirror-parent-field fom))
3639 (defun yas--calculate-adjacencies (snippet)
3640 "Calculate adjacencies for fields or mirrors of SNIPPET.
3642 This is according to their relative positions in the buffer, and
3643 has to be called before the $-constructs are deleted."
3644 (let* ((fom-set-next-fom
3645 (lambda (fom nextfom)
3646 (cond ((yas--field-p fom)
3647 (setf (yas--field-next fom) nextfom))
3648 ((yas--mirror-p fom)
3649 (setf (yas--mirror-next fom) nextfom))
3651 (setf (yas--exit-next fom) nextfom)))))
3654 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3655 (yas--mirror-p fom2)
3656 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3657 (link-foms fom-set-next-fom))
3658 ;; make some yas--field, yas--mirror and yas--exit soup
3660 (when (yas--snippet-exit snippet)
3661 (push (yas--snippet-exit snippet) soup))
3662 (dolist (field (yas--snippet-fields snippet))
3664 (dolist (mirror (yas--field-mirrors field))
3665 (push mirror soup)))
3667 (sort soup compare-fom-begs))
3669 (reduce link-foms soup)))))
3671 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3672 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3674 Use the tightest containing field if more than one field contains
3675 the mirror. Intended to be called *before* the dollar-regions are
3677 (let ((min (point-min))
3679 (dolist (field (yas--snippet-fields snippet))
3680 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3681 (<= (yas--mirror-end mirror) (yas--field-end field))
3682 (< min (yas--field-start field))
3683 (< (yas--field-end field) max))
3684 (setq min (yas--field-start field)
3685 max (yas--field-end field))
3686 (setf (yas--mirror-parent-field mirror) field)))))
3688 (defun yas--advance-end-maybe (fom newend)
3689 "Maybe advance FOM's end to NEWEND if it needs it.
3693 * call `yas--advance-start-maybe' on FOM's next fom.
3695 * in case FOM is field call `yas--advance-end-maybe' on its parent
3698 Also, if FOM is an exit-marker, always call
3699 `yas--advance-start-maybe' on its next fom. This is because
3700 exit-marker have identical start and end markers."
3701 (cond ((and fom (< (yas--fom-end fom) newend))
3702 (set-marker (yas--fom-end fom) newend)
3703 (yas--advance-start-maybe (yas--fom-next fom) newend)
3704 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3706 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3708 (defun yas--advance-start-maybe (fom newstart)
3709 "Maybe advance FOM's start to NEWSTART if it needs it.
3711 If it does, also call `yas--advance-end-maybe' on FOM."
3712 (when (and fom (< (yas--fom-start fom) newstart))
3713 (set-marker (yas--fom-start fom) newstart)
3714 (yas--advance-end-maybe fom newstart)))
3716 (defun yas--advance-end-of-parents-maybe (field newend)
3717 "Like `yas--advance-end-maybe' but for parent fields.
3719 Only works for fields and doesn't care about the start of the
3720 next FOM. Works its way up recursively for parents of parents."
3722 (< (yas--field-end field) newend))
3723 (set-marker (yas--field-end field) newend)
3724 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3726 (defvar yas--dollar-regions nil
3727 "When expanding the snippet the \"parse-create\" functions add
3728 cons cells to this var.")
3730 (defvar yas--backquote-markers-and-strings nil
3731 "List of (MARKER . STRING) marking where the values from
3732 backquoted Lisp expressions should be inserted at the end of
3735 (defun yas--snippet-parse-create (snippet)
3736 "Parse a recently inserted snippet template, creating all
3737 necessary fields, mirrors and exit points.
3739 Meant to be called in a narrowed buffer, does various passes"
3740 (let ((parse-start (point)))
3741 ;; Reset the yas--dollar-regions
3743 (setq yas--dollar-regions nil)
3744 ;; protect just the backquotes
3746 (yas--protect-escapes nil '(?`))
3747 ;; replace all backquoted expressions
3749 (goto-char parse-start)
3750 (yas--save-backquotes)
3751 ;; protect escaped characters
3753 (yas--protect-escapes)
3754 ;; parse fields with {}
3756 (goto-char parse-start)
3757 (yas--field-parse-create snippet)
3758 ;; parse simple mirrors and fields
3760 (goto-char parse-start)
3761 (yas--simple-mirror-parse-create snippet)
3762 ;; parse mirror transforms
3764 (goto-char parse-start)
3765 (yas--transform-mirror-parse-create snippet)
3766 ;; calculate adjacencies of fields and mirrors
3768 (yas--calculate-adjacencies snippet)
3769 ;; Delete $-constructs
3771 (save-restriction (widen) (yas--delete-regions yas--dollar-regions))
3772 ;; restore backquoted expression values
3774 (yas--restore-backquotes)
3777 (goto-char parse-start)
3778 (yas--restore-escapes)
3779 ;; update mirrors for the first time
3781 (yas--update-mirrors snippet)
3782 ;; indent the best we can
3784 (goto-char parse-start)
3785 (yas--indent snippet)))
3787 (defun yas--indent-according-to-mode (snippet-markers)
3788 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3789 ;;; Apropos indenting problems....
3791 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3792 ;; is available. Some implementations of these functions delete text
3793 ;; before they insert. If there happens to be a marker just after
3794 ;; the text being deleted, the insertion actually happens after the
3795 ;; marker, which misplaces it.
3797 ;; This would also happen if we had used overlays with the
3798 ;; `front-advance' property set to nil.
3800 ;; This is why I have these `trouble-markers', they are the ones at
3801 ;; they are the ones at the first non-whitespace char at the line
3802 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3803 ;; we should be at the correct to restore them to. All other
3804 ;; non-trouble-markers have been *pushed* and don't need special
3807 (goto-char (yas--real-line-beginning))
3808 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3814 (indent-according-to-mode)
3815 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3817 (mapc #'(lambda (marker)
3818 (set-marker marker (point)))
3821 (defvar yas--indent-original-column nil)
3822 (defun yas--indent (snippet)
3823 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3824 ;; Look for those $>
3826 (while (re-search-forward "$>" nil t)
3827 (delete-region (match-beginning 0) (match-end 0))
3828 (when (not (eq yas-indent-line 'auto))
3829 (yas--indent-according-to-mode snippet-markers))))
3830 ;; Now do stuff for 'fixed and 'auto
3832 (cond ((eq yas-indent-line 'fixed)
3833 (while (and (zerop (forward-line))
3834 (zerop (current-column)))
3835 (indent-to-column yas--indent-original-column)))
3836 ((eq yas-indent-line 'auto)
3837 (let ((end (set-marker (make-marker) (point-max)))
3838 (indent-first-line-p yas-also-auto-indent-first-line))
3839 (while (and (zerop (if indent-first-line-p
3842 (setq indent-first-line-p nil))
3846 (yas--indent-according-to-mode snippet-markers))))
3850 (defun yas--collect-snippet-markers (snippet)
3851 "Make a list of all the markers used by SNIPPET."
3853 (dolist (field (yas--snippet-fields snippet))
3854 (push (yas--field-start field) markers)
3855 (push (yas--field-end field) markers)
3856 (dolist (mirror (yas--field-mirrors field))
3857 (push (yas--mirror-start mirror) markers)
3858 (push (yas--mirror-end mirror) markers)))
3859 (let ((snippet-exit (yas--snippet-exit snippet)))
3860 (when (and snippet-exit
3861 (marker-buffer (yas--exit-marker snippet-exit)))
3862 (push (yas--exit-marker snippet-exit) markers)))
3865 (defun yas--real-line-beginning ()
3866 (let ((c (char-after (line-beginning-position)))
3867 (n (line-beginning-position)))
3868 (while (or (eql c ?\ )
3871 (setq c (char-after n)))
3874 (defun yas--escape-string (escaped)
3875 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3877 (defun yas--protect-escapes (&optional text escaped)
3878 "Protect all escaped characters with their numeric ASCII value.
3880 With optional string TEXT do it in string instead of buffer."
3881 (let ((changed-text text)
3882 (text-provided-p text))
3883 (mapc #'(lambda (escaped)
3885 (yas--replace-all (concat "\\" (char-to-string escaped))
3886 (yas--escape-string escaped)
3887 (when text-provided-p changed-text))))
3888 (or escaped yas--escaped-characters))
3891 (defun yas--restore-escapes (&optional text escaped)
3892 "Restore all escaped characters from their numeric ASCII value.
3894 With optional string TEXT do it in string instead of the buffer."
3895 (let ((changed-text text)
3896 (text-provided-p text))
3897 (mapc #'(lambda (escaped)
3899 (yas--replace-all (yas--escape-string escaped)
3900 (char-to-string escaped)
3901 (when text-provided-p changed-text))))
3902 (or escaped yas--escaped-characters))
3905 (defun yas--save-backquotes ()
3906 "Save all the \"`(lisp-expression)`\"-style expressions
3907 with their evaluated value into `yas--backquote-markers-and-strings'."
3908 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3909 (let ((current-string (match-string-no-properties 1)) transformed)
3910 (save-restriction (widen)
3911 (delete-region (match-beginning 0) (match-end 0)))
3912 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3913 (goto-char (match-beginning 0))
3915 (let ((marker (make-marker)))
3916 (insert "Y") ;; quite horrendous, I love it :)
3917 (set-marker marker (point))
3919 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3921 (defun yas--restore-backquotes ()
3922 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3923 (while yas--backquote-markers-and-strings
3924 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3925 (marker (car marker-and-string))
3926 (string (cdr marker-and-string)))
3932 (set-marker marker nil)))))
3934 (defun yas--scan-sexps (from count)
3936 (with-syntax-table (standard-syntax-table)
3937 (scan-sexps from count))
3941 (defun yas--make-marker (pos)
3942 "Create a marker at POS with nil `marker-insertion-type'."
3943 (let ((marker (set-marker (make-marker) pos)))
3944 (set-marker-insertion-type marker nil)
3947 (defun yas--field-parse-create (snippet &optional parent-field)
3948 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
3950 The following count as a field:
3952 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3954 * \"${n: text$(expression)}, the same with a Lisp expression;
3955 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
3957 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3959 When multiple expressions are found, only the last one counts."
3962 (while (re-search-forward yas--field-regexp nil t)
3963 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
3964 (number (and (match-string-no-properties 1)
3965 (string-to-number (match-string-no-properties 1))))
3966 (brand-new-field (and real-match-end-0
3967 ;; break if on "$(" immediately
3968 ;; after the ":", this will be
3969 ;; caught as a mirror with
3971 (not (save-match-data
3972 (eq (string-match "$[ \t\n]*("
3973 (match-string-no-properties 2)) 0)))
3974 ;; allow ${0: some exit text}
3975 ;; (not (and number (zerop number)))
3976 (yas--make-field number
3977 (yas--make-marker (match-beginning 2))
3978 (yas--make-marker (1- real-match-end-0))
3980 (when brand-new-field
3981 (goto-char real-match-end-0)
3982 (push (cons (1- real-match-end-0) real-match-end-0)
3983 yas--dollar-regions)
3984 (push (cons (match-beginning 0) (match-beginning 2))
3985 yas--dollar-regions)
3986 (push brand-new-field (yas--snippet-fields snippet))
3989 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
3990 (goto-char (point-min))
3991 (yas--field-parse-create snippet brand-new-field)))))))
3992 ;; if we entered from a parent field, now search for the
3993 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
3994 ;; primary field transformations
3998 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
3999 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4000 ;; commit the primary field transformation if:
4002 ;; 1. we don't find it in yas--dollar-regions (a subnested
4003 ;; field) might have already caught it.
4005 ;; 2. we really make sure we have either two '$' or some
4006 ;; text and a '$' after the colon ':'. This is a FIXME: work
4007 ;; my regular expressions and end these ugly hacks.
4009 (when (and real-match-end-1
4010 (not (member (cons (match-beginning 0)
4012 yas--dollar-regions))
4014 (char-before (1- (match-beginning 1))))))
4015 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4017 (setf (yas--field-transform parent-field)
4018 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4019 (push (cons (match-beginning 0) real-match-end-1)
4020 yas--dollar-regions)))))))
4022 (defun yas--transform-mirror-parse-create (snippet)
4023 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4024 (while (re-search-forward yas--transform-mirror-regexp nil t)
4025 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4026 (number (string-to-number (match-string-no-properties 1)))
4028 (not (zerop number))
4029 (yas--snippet-find-field snippet number)))
4031 (and real-match-end-0
4033 (yas--make-mirror (yas--make-marker (match-beginning 0))
4034 (yas--make-marker (match-beginning 0))
4036 (yas--restore-escapes
4037 (buffer-substring-no-properties (match-beginning 2)
4038 (1- real-match-end-0))))))))
4039 (when brand-new-mirror
4040 (push brand-new-mirror
4041 (yas--field-mirrors field))
4042 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4043 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4045 (defun yas--simple-mirror-parse-create (snippet)
4046 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4047 (while (re-search-forward yas--simple-mirror-regexp nil t)
4048 (let ((number (string-to-number (match-string-no-properties 1))))
4049 (cond ((zerop number)
4051 (setf (yas--snippet-exit snippet)
4052 (yas--make-exit (yas--make-marker (match-end 0))))
4054 (goto-char (match-beginning 0))
4055 (when yas-wrap-around-region
4056 (cond (yas-selected-text
4057 (insert yas-selected-text))
4058 ((and (eq yas-wrap-around-region 'cua)
4061 (insert (prog1 (get-register ?0)
4062 (set-register ?0 nil))))))
4063 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4064 yas--dollar-regions)))
4066 (let ((field (yas--snippet-find-field snippet number)))
4068 (let ((brand-new-mirror (yas--make-mirror
4069 (yas--make-marker (match-beginning 0))
4070 (yas--make-marker (match-beginning 0))
4072 (push brand-new-mirror
4073 (yas--field-mirrors field))
4074 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4075 (push (yas--make-field number
4076 (yas--make-marker (match-beginning 0))
4077 (yas--make-marker (match-beginning 0))
4079 (yas--snippet-fields snippet))))
4080 (push (cons (match-beginning 0) (match-end 0))
4081 yas--dollar-regions))))))
4083 (defun yas--delete-regions (regions)
4084 "Sort disjuct REGIONS by start point, then delete from the back."
4085 (mapc #'(lambda (reg)
4086 (delete-region (car reg) (cdr reg)))
4089 (>= (car r1) (car r2))))))
4091 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4092 (let* ((parent (yas--mirror-parent-field mirror))
4093 (parents-mirrors (and parent
4094 (yas--field-mirrors parent))))
4095 (or (yas--mirror-depth mirror)
4096 (setf (yas--mirror-depth mirror)
4097 (cond ((memq mirror traversed)
4099 ((and parent parents-mirrors)
4101 (mapcar #'(lambda (m)
4102 (yas--calculate-mirror-depth m
4111 (defun yas--update-mirrors (snippet)
4112 "Update all the mirrors of SNIPPET."
4114 (dolist (field-and-mirror (sort
4115 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4116 ;; where F is the field that M is mirroring
4118 (mapcan #'(lambda (field)
4119 (mapcar #'(lambda (mirror)
4120 (cons field mirror))
4121 (yas--field-mirrors field)))
4122 (yas--snippet-fields snippet))
4123 ;; then sort this list so that entries with mirrors with parent
4124 ;; fields appear before. This was important for fixing #290, and
4125 ;; luckily also handles the case where a mirror in a field causes
4126 ;; another mirror to need reupdating
4128 #'(lambda (field-and-mirror1 field-and-mirror2)
4129 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4130 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4131 (let* ((field (car field-and-mirror))
4132 (mirror (cdr field-and-mirror))
4133 (parent-field (yas--mirror-parent-field mirror)))
4134 ;; before updating a mirror with a parent-field, maybe advance
4138 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4139 ;; update this mirror
4141 (yas--mirror-update-display mirror field)
4142 ;; `yas--place-overlays' is needed if the active field and
4143 ;; protected overlays have been changed because of insertions
4144 ;; in `yas--mirror-update-display'
4146 (when (eq field (yas--snippet-active-field snippet))
4147 (yas--place-overlays snippet field))))))
4149 (defun yas--mirror-update-display (mirror field)
4150 "Update MIRROR according to FIELD (and mirror transform)."
4152 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4153 (reflection (and (not (and mirror-parent-field
4154 (yas--field-modified-p mirror-parent-field)))
4155 (or (yas--apply-transform mirror field 'empty-on-nil)
4156 (yas--field-text-for-display field)))))
4157 (when (and reflection
4158 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4159 (yas--mirror-end mirror)))))
4160 (goto-char (yas--mirror-start mirror))
4161 (yas--inhibit-overlay-hooks
4162 (insert reflection))
4163 (if (> (yas--mirror-end mirror) (point))
4164 (delete-region (point) (yas--mirror-end mirror))
4165 (set-marker (yas--mirror-end mirror) (point))
4166 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4167 ;; super-special advance
4168 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4170 (defun yas--field-update-display (field)
4171 "Much like `yas--mirror-update-display', but for fields."
4172 (when (yas--field-transform field)
4173 (let ((transformed (and (not (eq (yas--field-number field) 0))
4174 (yas--apply-transform field field))))
4175 (when (and transformed
4176 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4177 (yas--field-end field)))))
4178 (setf (yas--field-modified-p field) t)
4179 (goto-char (yas--field-start field))
4180 (yas--inhibit-overlay-hooks
4181 (insert transformed)
4182 (if (> (yas--field-end field) (point))
4183 (delete-region (point) (yas--field-end field))
4184 (set-marker (yas--field-end field) (point))
4185 (yas--advance-start-maybe (yas--field-next field) (point)))
4189 ;;; Post-command hook:
4191 (defun yas--post-command-handler ()
4192 "Handles various yasnippet conditions after each command."
4193 (cond (yas--protection-violation
4194 (goto-char yas--protection-violation)
4195 (setq yas--protection-violation nil))
4196 ((eq 'undo this-command)
4198 ;; After undo revival the correct field is sometimes not
4199 ;; restored correctly, this condition handles that
4201 (let* ((snippet (car (yas--snippets-at-point)))
4202 (target-field (and snippet
4203 (find-if-not #'(lambda (field)
4204 (yas--field-probably-deleted-p snippet field))
4206 (cons (yas--snippet-active-field snippet)
4207 (yas--snippet-fields snippet)))))))
4209 (yas--move-to-field snippet target-field))))
4210 ((not (yas--undo-in-progress))
4211 ;; When not in an undo, check if we must commit the snippet
4212 ;; (user exited it).
4213 (yas--check-commit-snippet))))
4217 ;; The docstrings for some functions are generated dynamically
4218 ;; depending on the context.
4220 (put 'yas-expand 'function-documentation
4221 '(yas--expand-from-trigger-key-doc t))
4222 (defun yas--expand-from-trigger-key-doc (context)
4223 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4224 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4225 (fallback-description
4226 (cond ((eq yas-fallback-behavior 'call-other-command)
4227 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4229 (format "call command `%s'."
4230 (pp-to-string fallback)))
4231 "do nothing (`yas-expand' doesn't shadow\nanything).")))
4232 ((eq yas-fallback-behavior 'return-nil)
4234 (t "defer to `yas-fallback-behavior' (which see)."))))
4235 (concat "Expand a snippet before point. If no snippet
4236 expansion is possible, "
4237 fallback-description
4238 "\n\nOptional argument FIELD is for non-interactive use and is an
4239 object satisfying `yas--field-p' to restrict the expansion to.")))
4241 (put 'yas-expand-from-keymap 'function-documentation
4242 '(yas--expand-from-keymap-doc t))
4243 (defun yas--expand-from-keymap-doc (context)
4244 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4245 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4246 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4247 (when (and context (eq this-command 'describe-key))
4248 (let* ((vec (this-single-command-keys))
4249 (templates (mapcan #'(lambda (table)
4250 (yas--fetch table vec))
4251 (yas--get-snippet-tables)))
4252 (yas--direct-keymaps nil)
4253 (fallback (key-binding vec)))
4254 (concat "In this case, "
4256 (concat "these snippets are bound to this key:\n"
4257 (yas--template-pretty-list templates)
4258 "\n\nIf none of these expands, "))
4260 (format "fallback `%s' will be called." (pp-to-string fallback)))
4261 "no fallback keybinding is called."))))))
4263 (defun yas--template-pretty-list (templates)
4265 (yas-buffer-local-condition 'always))
4266 (dolist (plate templates)
4267 (setq acc (concat acc "\n*) "
4268 (propertize (concat "\\\\snippet `" (car plate) "'")
4269 'yasnippet (cdr plate)))))
4272 (define-button-type 'help-snippet-def
4273 :supertype 'help-xref
4274 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4275 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4277 (defun yas--snippet-description-finish-runonce ()
4278 "Final adjustments for the help buffer when snippets are concerned."
4279 (yas--create-snippet-xrefs)
4280 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4282 (defun yas--create-snippet-xrefs ()
4284 (goto-char (point-min))
4285 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4286 (let ((template (get-text-property (match-beginning 1)
4289 (help-xref-button 1 'help-snippet-def template)
4290 (kill-region (match-end 1) (match-end 0))
4291 (kill-region (match-beginning 0) (match-beginning 1)))))))
4295 (defvar yas-verbosity 4
4296 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4298 (defun yas--message (level message &rest args)
4299 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4300 (when (> yas-verbosity level)
4301 (message "%s" (apply #'yas--format message args))))
4303 (defun yas--format (format-control &rest format-args)
4304 (apply #'format (concat "[yas] " format-control) format-args))
4311 ;; `locate-dominating-file'
4312 ;; `region-active-p'
4314 ;; added for compatibility in emacsen < 23
4315 (unless (>= emacs-major-version 23)
4316 (unless (fboundp 'region-active-p)
4317 (defun region-active-p () (and transient-mark-mode mark-active)))
4319 (unless (fboundp 'locate-dominating-file)
4320 (defvar locate-dominating-stop-dir-regexp
4321 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4322 "Regexp of directory names which stop the search in `locate-dominating-file'.
4323 Any directory whose name matches this regexp will be treated like
4324 a kind of root directory by `locate-dominating-file' which will stop its search
4325 when it bumps into it.
4326 The default regexp prevents fruitless and time-consuming attempts to find
4327 special files in directories in which filenames are interpreted as hostnames,
4328 or mount points potentially requiring authentication as a different user.")
4330 (defun locate-dominating-file (file name)
4331 "Look up the directory hierarchy from FILE for a file named NAME.
4332 Stop at the first parent directory containing a file NAME,
4333 and return the directory. Return nil if not found."
4334 ;; We used to use the above locate-dominating-files code, but the
4335 ;; directory-files call is very costly, so we're much better off doing
4336 ;; multiple calls using the code in here.
4338 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4339 ;; `name' in /home or in /.
4340 (setq file (abbreviate-file-name file))
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 file (file-name-directory
4359 (directory-file-name file))))
4364 ;;; Backward compatibility to yasnippet <= 0.7
4366 (defvar yas--backported-syms '(;; `defcustom's
4369 yas-prompt-functions
4371 yas-also-auto-indent-first-line
4373 yas-triggers-in-field
4374 yas-fallback-behavior
4375 yas-choose-keys-first
4376 yas-choose-tables-first
4379 yas-wrap-around-region
4382 yas-expand-only-for-last-commands
4383 yas-field-highlight-face
4385 ;; these vars can be customized as well
4391 yas-after-exit-snippet-hook
4392 yas-before-expand-snippet-hook
4393 yas-buffer-local-condition
4396 ;; prompting functions
4401 yas-completing-prompt
4404 ;; interactive functions
4409 yas-direct-keymaps-reload
4413 yas-compile-directory
4416 yas-expand-from-trigger-key
4417 yas-expand-from-keymap
4419 yas-visit-snippet-file
4421 yas-load-snippet-buffer
4424 yas-next-field-or-maybe-expand
4429 yas-exit-all-snippets
4430 yas-skip-and-clear-or-delete-char
4432 ;; symbols that I "exported" for use
4433 ;; in snippets and hookage
4450 yas-default-from-field
4453 yas-define-condition-cache
4454 yas-hippie-try-expand
4456 ;; debug definitions
4457 ;; yas-debug-snippet-vars
4458 ;; yas-exterminate-package
4461 ;; testing definitions
4462 ;; yas-should-expand
4463 ;; yas-should-not-expand
4465 ;; yas-make-file-or-dirs
4467 ;; yas-saving-variables
4468 ;; yas-call-with-snippet-dirs
4469 ;; yas-with-snippet-dirs
4471 "Backported yasnippet symbols.
4473 They are mapped to \"yas/*\" variants.")
4475 (dolist (sym yas--backported-syms)
4476 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4478 (make-obsolete-variable backported sym "yasnippet 0.8")
4479 (defvaralias backported sym))
4481 (make-obsolete backported sym "yasnippet 0.8")
4482 (defalias backported sym))))
4484 (defvar yas--exported-syms
4486 (mapatoms (lambda (atom)
4487 (if (and (or (and (boundp atom)
4488 (not (get atom 'byte-obsolete-variable)))
4490 (not (get atom 'byte-obsolete-info))))
4491 (string-match-p "^yas-[^-]" (symbol-name atom)))
4492 (push atom exported))))
4494 "Exported yasnippet symbols.
4496 i.e. the ones with \"yas-\" single dash prefix. I will try to
4497 keep them in future yasnippet versions and other elisp libraries
4498 can more or less safely rely upon them.")
4501 (provide 'yasnippet)
4503 ;;; yasnippet.el ends here
4506 ;; byte-compile-warnings: (not cl-functions)