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
136 (defvar yas--editing-template)
137 (defvar yas--guessed-modes)
138 (defvar yas--indent-original-column)
139 (defvar yas--scheduled-jit-loads)
141 (defvar yas-selected-text)
142 (defvar yas-verbosity)
143 (defvar yas--current-template)
146 ;;; User customizable variables
148 (defgroup yasnippet nil
149 "Yet Another Snippet extension"
152 (defvar yas--load-file-name load-file-name
153 "Store the filename that yasnippet.el was originally loaded from.")
155 (defcustom yas-snippet-dirs (remove nil
156 (list "~/.emacs.d/snippets"
157 (when yas--load-file-name
158 (concat (file-name-directory yas--load-file-name) "snippets"))))
159 "Directory or list of snippet dirs for each major mode.
161 The directory where user-created snippets are to be stored. Can
162 also be a list of directories. In that case, when used for
163 bulk (re)loading of snippets (at startup or via
164 `yas-reload-all'), directories appearing earlier in the list
165 shadow other dir's snippets. Also, the first directory is taken
166 as the default for storing the user's new snippets."
167 :type '(choice (string :tag "Single directory (string)")
168 (repeat :args (string) :tag "List of directories (strings)"))
171 :set #'(lambda (symbol new)
172 (let ((old (and (boundp symbol)
173 (symbol-value symbol))))
174 (set-default symbol new)
175 (unless (or (not (fboundp 'yas-reload-all))
179 (defun yas-snippet-dirs ()
180 "Return `yas-snippet-dirs' (which see) as a list."
181 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
183 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
185 (defcustom yas-new-snippet-default "\
186 # -*- mode: snippet -*-
188 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
189 # binding: ${4:direct-keybinding}}${5:
190 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
194 "Default snippet to use when creating a new snippet.
195 If nil, don't use any snippet."
199 (defcustom yas-prompt-functions '(yas-x-prompt
201 yas-completing-prompt
204 "Functions to prompt for keys, templates, etc interactively.
206 These functions are called with the following arguments:
208 - PROMPT: A string to prompt the user
210 - CHOICES: a list of strings or objects.
212 - optional DISPLAY-FN : A function that, when applied to each of
213 the objects in CHOICES will return a string.
215 The return value of any function you put here should be one of
216 the objects in CHOICES, properly formatted with DISPLAY-FN (if
219 - To signal that your particular style of prompting is
220 unavailable at the moment, you can also have the function return
223 - To signal that the user quit the prompting process, you can
226 (signal 'quit \"user quit!\")."
227 :type '(repeat function)
230 (defcustom yas-indent-line 'auto
231 "Controls indenting applied to a recent snippet expansion.
233 The following values are possible:
235 - `fixed' Indent the snippet to the current column;
237 - `auto' Indent each line of the snippet with `indent-according-to-mode'
239 Every other value means don't apply any snippet-side indentation
240 after expansion (the manual per-line \"$>\" indentation still
242 :type '(choice (const :tag "Nothing" nothing)
243 (const :tag "Fixed" fixed)
244 (const :tag "Auto" auto))
247 (defcustom yas-also-auto-indent-first-line nil
248 "Non-nil means also auto indent first line according to mode.
250 Naturally this is only valid when `yas-indent-line' is `auto'"
254 (defcustom yas-snippet-revival t
255 "Non-nil means re-activate snippet fields after undo/redo."
259 (defcustom yas-triggers-in-field nil
260 "If non-nil, allow stacked expansions (snippets inside snippets).
262 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
267 (defcustom yas-fallback-behavior 'call-other-command
268 "How to act when `yas-expand' does *not* expand a snippet.
270 - `call-other-command' means try to temporarily disable YASnippet
271 and call the next command bound to whatever key was used to
274 - nil or the symbol `return-nil' mean do nothing. (and
275 `yas-expand' returns nil)
277 - A Lisp form (apply COMMAND . ARGS) means interactively call
278 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
279 with ARGS as arguments."
280 :type '(choice (const :tag "Call previous command" call-other-command)
281 (const :tag "Do nothing" return-nil))
284 (defcustom yas-choose-keys-first nil
285 "If non-nil, prompt for snippet key first, then for template.
287 Otherwise prompts for all possible snippet names.
289 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
293 (defcustom yas-choose-tables-first nil
294 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
296 Otherwise, user chooses between the merging together of all
299 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
303 (defcustom yas-use-menu 'abbreviate
304 "Display a YASnippet menu in the menu bar.
306 When non-nil, submenus for each snippet table will be listed
307 under the menu \"Yasnippet\".
309 - If set to `abbreviate', only the current major-mode
310 menu and the modes set in `yas--extra-modes' are listed.
312 - If set to `full', every submenu is listed
314 - It set to nil, don't display a menu at all (this requires a
315 `yas-reload-all' call if the menu is already visible).
317 Any other non-nil value, every submenu is listed."
318 :type '(choice (const :tag "Full" full)
319 (const :tag "Abbreviate" abbreviate)
320 (const :tag "No menu" nil))
323 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
325 (char-to-string ?\x21E5))) ;; little ->| sign
327 "The text that will be used in menu to represent the trigger."
331 (defcustom yas-wrap-around-region nil
332 "If non-nil, snippet expansion wraps around selected region.
334 The wrapping occurs just before the snippet's exit marker. This
335 can be overridden on a per-snippet basis."
339 (defcustom yas-good-grace t
340 "If non-nil, don't raise errors in inline elisp evaluation.
342 An error string \"[yas] error\" is returned instead."
346 (defcustom yas-visit-from-menu nil
347 "If non-nil visit snippets's files from menu, instead of expanding them.
349 This can only work when snippets are loaded from files."
353 (defcustom yas-expand-only-for-last-commands nil
354 "List of `last-command' values to restrict tab-triggering to, or nil.
356 Leave this set at nil (the default) to be able to trigger an
357 expansion simply by placing the cursor after a valid tab trigger,
358 using whichever commands.
360 Optionally, set this to something like '(self-insert-command) if
361 you to wish restrict expansion to only happen when the last
362 letter of the snippet tab trigger was typed immediately before
363 the trigger key itself."
364 :type '(repeat function)
367 ;; Only two faces, and one of them shouldn't even be used...
369 (defface yas-field-highlight-face
370 '((t (:inherit 'region)))
371 "The face used to highlight the currently active field of a snippet"
374 (defface yas--field-debug-face
376 "The face used for debugging some overlays normally hidden"
380 ;;; User-visible variables
382 (defvar yas-keymap (let ((map (make-sparse-keymap)))
383 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
384 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
385 (define-key map [(shift tab)] 'yas-prev-field)
386 (define-key map [backtab] 'yas-prev-field)
387 (define-key map (kbd "C-g") 'yas-abort-snippet)
388 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
390 "The active keymap while a snippet expansion is in progress.")
392 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
393 "List of character syntaxes used to find a trigger key before point.
394 The list is tried in the order while scanning characters
395 backwards from point. For example, if the list is '(\"w\" \"w_\")
396 first look for trigger keys which are composed exclusively of
397 \"word\"-syntax characters, and then, if that fails, look for
398 keys which are either of \"word\" or \"symbol\"
399 syntax. Triggering after
403 will, according to the \"w\" element first try \"bar\". If that
404 isn't a trigger key, \"foo-bar\" is tried, respecting a second
407 (defvar yas-after-exit-snippet-hook
409 "Hooks to run after a snippet exited.
411 The hooks will be run in an environment where some variables bound to
414 `yas-snippet-beg' : The beginning of the region of the snippet.
416 `yas-snippet-end' : Similar to beg.
418 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
420 (defvar yas-before-expand-snippet-hook
422 "Hooks to run just before expanding a snippet.")
424 (defvar yas-buffer-local-condition
425 '(if (and (or (fourth (syntax-ppss))
426 (fifth (syntax-ppss)))
428 (eq this-command 'yas-expand-from-trigger-key))
429 '(require-snippet-condition . force-in-comment)
431 "Snippet expanding condition.
433 This variable is a Lisp form which is evaluated every time a
434 snippet expansion is attempted:
436 * If it evaluates to nil, no snippets can be expanded.
438 * If it evaluates to the a cons (require-snippet-condition
441 * Snippets bearing no \"# condition:\" directive are not
444 * Snippets bearing conditions that evaluate to nil (or
445 produce an error) won't be considered.
447 * If the snippet has a condition that evaluates to non-nil
450 * If REQUIREMENT is t, the snippet is considered
452 * If REQUIREMENT is `eq' RESULT, the snippet is
455 * Otherwise, the snippet is not considered.
457 * If it evaluates to the symbol 'always, all snippets are
458 considered for expansion, regardless of any conditions.
460 * If it evaluates to t or some other non-nil value
462 * Snippet bearing no conditions, or conditions that
463 evaluate to non-nil, are considered for expansion.
465 * Otherwise, the snippet is not considered.
467 Here's an example preventing snippets from being expanded from
468 inside comments, in `python-mode' only, with the exception of
469 snippets returning the symbol 'force-in-comment in their
472 (add-hook 'python-mode-hook
474 (setq yas-buffer-local-condition
475 '(if (python-in-string/comment)
476 '(require-snippet-condition . force-in-comment)
479 The default value is similar, it filters out potential snippet
480 expansions inside comments and string literals, unless the
481 snippet itself contains a condition that returns the symbol
482 `force-in-comment'.")
485 ;;; Internal variables
487 (defvar yas--version "0.8.0beta")
489 (defvar yas--menu-table (make-hash-table)
490 "A hash table of MAJOR-MODE symbols to menu keymaps.")
492 (defvar yas--known-modes
493 '(ruby-mode rst-mode markdown-mode)
494 "A list of mode which is well known but not part of Emacs.")
496 (defvar yas--escaped-characters
497 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
498 "List of characters which *might* need to be escaped.")
500 (defconst yas--field-regexp
501 "${\\([0-9]+:\\)?\\([^}]*\\)}"
502 "A regexp to *almost* recognize a field.")
504 (defconst yas--multi-dollar-lisp-expression-regexp
505 "$+[ \t\n]*\\(([^)]*)\\)"
506 "A regexp to *almost* recognize a \"$(...)\" expression.")
508 (defconst yas--backquote-lisp-expression-regexp
510 "A regexp to recognize a \"`lisp-expression`\" expression." )
512 (defconst yas--transform-mirror-regexp
513 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
514 "A regexp to *almost* recognize a mirror with a transform.")
516 (defconst yas--simple-mirror-regexp
518 "A regexp to recognize a simple mirror.")
520 (defvar yas--snippet-id-seed 0
521 "Contains the next id for a snippet.")
523 (defun yas--snippet-next-id ()
524 (let ((id yas--snippet-id-seed))
525 (incf yas--snippet-id-seed)
531 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
532 (defvar last-buffer-undo-list nil)
534 (defvar yas--minor-mode-menu nil
535 "Holds the YASnippet menu.")
537 (defun yas--init-minor-keymap ()
538 "Set up the `yas-minor-mode' keymap."
539 (let ((map (make-sparse-keymap)))
541 (easy-menu-define yas--minor-mode-menu
543 "Menu used when `yas-minor-mode' is active."
546 ["Expand trigger" yas-expand
547 :help "Possibly expand tab trigger before point"]
548 ["Insert at point..." yas-insert-snippet
549 :help "Prompt for an expandable snippet and expand it at point"]
550 ["New snippet..." yas-new-snippet
551 :help "Create a new snippet in an appropriate directory"]
552 ["Visit snippet file..." yas-visit-snippet-file
553 :help "Prompt for an expandable snippet and find its file"]
555 ("Snippet menu behaviour"
556 ["Visit snippets" (setq yas-visit-from-menu t)
557 :help "Visit snippets from the menu"
558 :active t :style radio :selected yas-visit-from-menu]
559 ["Expand snippets" (setq yas-visit-from-menu nil)
560 :help "Expand snippets from the menu"
561 :active t :style radio :selected (not yas-visit-from-menu)]
563 ["Show all known modes" (setq yas-use-menu 'full)
564 :help "Show one snippet submenu for each loaded table"
565 :active t :style radio :selected (eq yas-use-menu 'full)]
566 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
567 :help "Show only snippet submenus for the current active modes"
568 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
570 ["Auto" (setq yas-indent-line 'auto)
571 :help "Indent each line of the snippet with `indent-according-to-mode'"
572 :active t :style radio :selected (eq yas-indent-line 'auto)]
573 ["Fixed" (setq yas-indent-line 'fixed)
574 :help "Indent the snippet to the current column"
575 :active t :style radio :selected (eq yas-indent-line 'fixed)]
576 ["None" (setq yas-indent-line 'none)
577 :help "Don't apply any particular snippet indentation after expansion"
578 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
580 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
581 (not yas-also-auto-indent-first-line))
582 :help "When auto-indenting also, auto indent the first line menu"
583 :active (eq yas-indent-line 'auto)
584 :style toggle :selected yas-also-auto-indent-first-line]
587 ["System X-widget" (setq yas-prompt-functions
589 (remove 'yas-x-prompt
590 yas-prompt-functions)))
591 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
592 :active t :style radio :selected (eq (car yas-prompt-functions)
594 ["Dropdown-list" (setq yas-prompt-functions
595 (cons 'yas-dropdown-prompt
596 (remove 'yas-dropdown-prompt
597 yas-prompt-functions)))
598 :help "Use a special dropdown list"
599 :active t :style radio :selected (eq (car yas-prompt-functions)
600 'yas-dropdown-prompt)]
601 ["Ido" (setq yas-prompt-functions
602 (cons 'yas-ido-prompt
603 (remove 'yas-ido-prompt
604 yas-prompt-functions)))
605 :help "Use an ido-style minibuffer prompt"
606 :active t :style radio :selected (eq (car yas-prompt-functions)
608 ["Completing read" (setq yas-prompt-functions
609 (cons 'yas-completing-prompt
610 (remove 'yas-completing-prompt
611 yas-prompt-functions)))
612 :help "Use a normal minibuffer prompt"
613 :active t :style radio :selected (eq (car yas-prompt-functions)
614 'yas-completing-prompt)]
617 ["Wrap region in exit marker"
618 (setq yas-wrap-around-region
619 (not yas-wrap-around-region))
620 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
621 :style toggle :selected yas-wrap-around-region]
622 ["Allow stacked expansions "
623 (setq yas-triggers-in-field
624 (not yas-triggers-in-field))
625 :help "If non-nil allow snippets to be triggered inside other snippet fields"
626 :style toggle :selected yas-triggers-in-field]
627 ["Revive snippets on undo "
628 (setq yas-snippet-revival
629 (not yas-snippet-revival))
630 :help "If non-nil allow snippets to become active again after undo"
631 :style toggle :selected yas-snippet-revival]
634 (not yas-good-grace))
635 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
636 :style toggle :selected yas-good-grace]
639 ["Load snippets..." yas-load-directory
640 :help "Load snippets from a specific directory"]
641 ["Reload everything" yas-reload-all
642 :help "Cleanup stuff, reload snippets, rebuild menus"]
644 :help "Display some information about YASnippet"])))
646 ;; Now for the stuff that has direct keybindings
648 (define-key map [(tab)] 'yas-expand)
649 (define-key map (kbd "TAB") 'yas-expand)
650 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
651 (define-key map "\C-c&\C-n" 'yas-new-snippet)
652 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
655 (defvar yas-minor-mode-map (yas--init-minor-keymap)
656 "The keymap used when `yas-minor-mode' is active.")
658 (defvar yas--extra-modes nil
659 "An internal list of modes for which to also lookup snippets.
661 This variable probably makes more sense as buffer-local, so
662 ensure your use `make-local-variable' when you set it.")
663 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.8.1")
665 (defvar yas--tables (make-hash-table)
666 "A hash table of mode symbols to `yas--table' objects.")
668 (defvar yas--parents (make-hash-table)
669 "A hash table of mode symbols do lists of direct parent mode symbols.
671 This list is populated when reading the \".yas-parents\" files
672 found when traversing snippet directories with
673 `yas-load-directory'.
675 There might be additional parenting information stored in the
676 `derived-mode-parent' property of some mode symbols, but that is
679 (defvar yas--direct-keymaps (list)
680 "Keymap alist supporting direct snippet keybindings.
682 This variable is placed in `emulation-mode-map-alists'.
684 Its elements looks like (TABLE-NAME . KEYMAP). They're
685 instantiated on `yas-reload-all' but KEYMAP is added to only when
686 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
687 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
688 defined direct keybindings to the command
689 `yas-expand-from-keymap' which then which snippet to expand.")
691 (defun yas-direct-keymaps-reload ()
692 "Force reload the direct keybinding for active snippet tables."
694 (setq yas--direct-keymaps nil)
695 (maphash #'(lambda (name table)
696 (push (cons (intern (format "yas--direct-%s" name))
697 (yas--table-direct-keymap table))
698 yas--direct-keymaps))
701 (defun yas--modes-to-activate ()
702 "Compute list of mode symbols that are active for `yas-expand'
705 (setq dfs (lambda (mode &optional explored)
709 in (remove nil (cons (get mode
710 'derived-mode-parent)
711 (gethash mode yas--parents)))
713 unless (memq neighbour explored)
714 append (funcall dfs neighbour explored)))))
715 (remove-duplicates (append yas--extra-modes
716 (funcall dfs major-mode)))))
718 (defvar yas-minor-mode-hook nil
719 "Hook run when `yas-minor-mode' is turned on.")
722 (define-minor-mode yas-minor-mode
723 "Toggle YASnippet mode.
725 When YASnippet mode is enabled, `yas-expand', normally bound to
726 the TAB key, expands snippets of code depending on the major
729 With no argument, this command toggles the mode.
730 positive prefix argument turns on the mode.
731 Negative prefix argument turns off the mode.
734 \\{yas-minor-mode-map}"
736 ;; The indicator for the mode line.
739 (cond (yas-minor-mode
740 ;; Install the direct keymaps in `emulation-mode-map-alists'
741 ;; (we use `add-hook' even though it's not technically a hook,
742 ;; but it works). Then define variables named after modes to
743 ;; index `yas--direct-keymaps'.
745 ;; Also install the post-command-hook.
747 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
748 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
749 ;; Set the `yas--direct-%s' vars for direct keymap expansion
751 (dolist (mode (yas--modes-to-activate))
752 (let ((name (intern (format "yas--direct-%s" mode))))
753 (set-default name nil)
754 (set (make-local-variable name) t)))
757 (yas--load-pending-jits))
759 ;; Uninstall the direct keymaps and the post-command hook
761 (remove-hook 'post-command-hook 'yas--post-command-handler t)
762 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
764 (defun yas-activate-extra-mode (mode)
765 "Activates the snippets for the given `mode' in the buffer.
767 The function can be called in the hook of a minor mode to
768 activate snippets associated with that mode."
772 (maphash (lambda (k _)
773 (setq modes (cons (list k) modes)))
775 (setq symbol (completing-read
776 "Activate mode: " modes nil t))
778 (when (not (string= "" symbol))
781 (add-to-list (make-local-variable 'yas--extra-modes) mode)
782 (yas--load-pending-jits)))
784 (defun yas-deactivate-extra-mode (mode)
785 "Deactivates the snippets for the given `mode' in the buffer."
789 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
790 (set (make-local-variable 'yas--extra-modes)
794 (defvar yas-dont-activate '(minibufferp)
795 "If non-nil don't let `yas-global-mode' affect some buffers.
797 If a function of zero arguments, then its result is used.
799 If a list of functions, then all functions must return nil to
800 activate yas for this buffer.
802 In Emacsen <= 23, this variable is buffer-local. Because
803 `yas-minor-mode-on' is called by `yas-global-mode' after
804 executing the buffer's major mode hook, setting this variable
805 there is an effective way to define exceptions to the \"global\"
806 activation behaviour.
808 In Emacsen > 23, only the global value is used. To define
809 per-mode exceptions to the \"global\" activation behaviour, call
810 `yas-minor-mode' with a negative argument directily in the major
812 (unless (> emacs-major-version 23)
814 (make-variable-buffer-local 'yas-dont-activate)))
817 (defun yas-minor-mode-on ()
818 "Turn on YASnippet minor mode.
820 Honour `yas-dont-activate', which see."
822 ;; Check `yas-dont-activate'
823 (unless (cond ((functionp yas-dont-activate)
824 (funcall yas-dont-activate))
825 ((consp yas-dont-activate)
826 (some #'funcall yas-dont-activate))
831 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
835 (defun yas--global-mode-reload-with-jit-maybe ()
836 "Run `yas-reload-all' when `yas-global-mode' is on."
837 (when yas-global-mode (yas-reload-all)))
839 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
844 (defvar yas--font-lock-keywords
845 (append '(("^#.*$" . font-lock-comment-face))
846 lisp-font-lock-keywords-2
848 (0 font-lock-keyword-face)
849 (1 font-lock-string-face t))
851 (0 font-lock-keyword-face)
852 (1 font-lock-warning-face t))
853 ("${" . font-lock-keyword-face)
854 ("$[0-9]+?" . font-lock-preprocessor-face)
855 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
857 (0 font-lock-keyword-face)))))
859 (defvar snippet-mode-map
860 (let ((map (make-sparse-keymap)))
861 (easy-menu-define nil
863 "Menu used when snippet-mode is active."
865 (mapcar #'(lambda (ent)
867 (define-key map (third ent) (second ent)))
868 (vector (first ent) (second ent) t))
869 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
870 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
871 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
873 "The keymap used when `snippet-mode' is active.")
876 (define-derived-mode snippet-mode text-mode "Snippet"
877 "A mode for editing yasnippets"
878 (setq font-lock-defaults '(yas--font-lock-keywords))
879 (set (make-local-variable 'require-final-newline) nil)
880 (set (make-local-variable 'comment-start) "#")
881 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
885 ;;; Internal structs for template management
887 (defstruct (yas--template (:constructor yas--make-blank-template))
888 "A template for a snippet."
898 group ;; as dictated by the #group: directive or .yas-make-groups
899 perm-group ;; as dictated by `yas-define-menu'
903 (defun yas--populate-template (template &rest args)
904 "Helper function to populate TEMPLATE with properties."
907 (position (intern (substring (symbol-name (car args)) 1))
908 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
910 (setq args (cddr args)))
913 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
914 "A table to store snippets for a particular mode.
916 Has the following fields:
920 A symbol name normally corresponding to a major mode, but can
921 also be a pseudo major-mode to be used in
922 `yas-activate-extra-mode', for example.
926 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
927 a string or a vector, where the former is the snippet's trigger
928 and the latter means it's a direct keybinding. NAMEHASH is yet
929 another hash of (NAME . TEMPLATE) where NAME is the snippet's
930 name and TEMPLATE is a `yas--template' object.
932 `yas--table-direct-keymap'
934 A keymap for the snippets in this table that have direct
935 keybindings. This is kept in sync with the keyhash, i.e., all
936 the elements of the keyhash that are vectors appear here as
937 bindings to `yas-expand-from-keymap'.
939 `yas--table-uuidhash'
941 A hash table mapping snippets uuid's to the same `yas--template'
942 objects. A snippet uuid defaults to the snippet's name."
944 (hash (make-hash-table :test 'equal))
945 (uuidhash (make-hash-table :test 'equal))
947 (direct-keymap (make-sparse-keymap)))
949 (defun yas--get-template-by-uuid (mode uuid)
950 "Find the snippet template in MODE by its UUID."
951 (let* ((table (gethash mode yas--tables mode)))
953 (gethash uuid (yas--table-uuidhash table)))))
955 ;; Apropos storing/updating in TABLE, this works in two steps:
957 ;; 1. `yas--remove-template-by-uuid' removes any
958 ;; keyhash-namehash-template mappings from TABLE, grabbing the
959 ;; snippet by its uuid. Also removes mappings from TABLE's
960 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
961 ;; of potentially stale menu bindings right?.)
963 ;; 2. `yas--add-template' adds this all over again.
965 ;; Create a new or add to an existing keyhash-namehash mapping.
967 ;; For reference on understanding this, consider three snippet
970 ;; A: # name: The Foo
972 ;; # binding: C-c M-l
974 ;; B: # name: Mrs Foo
977 ;; C: # name: The Bar
978 ;; # binding: C-c M-l
983 ;; keyhash namehashes(3) yas--template structs(4)
984 ;; -----------------------------------------------------
987 ;; "foo" ---> "The Foo" ---> [yas--template A] |
988 ;; "Mrs Foo" ---> [yas--template B] |
990 ;; [C-c M-l] ---> "The Foo" -------------------------/
991 ;; "The Bar" ---> [yas--template C]
993 ;; "baz" ---> "Baz" ---> [yas--template D]
995 ;; Additionally, since uuid defaults to the name, we have a
996 ;; `yas--table-uuidhash' for TABLE
998 ;; uuidhash yas--template structs
999 ;; -------------------------------
1000 ;; "The Foo" ---> [yas--template A]
1001 ;; "Mrs Foo" ---> [yas--template B]
1002 ;; "The Bar" ---> [yas--template C]
1003 ;; "Baz" ---> [yas--template D]
1005 ;; FIXME: the more I look at this data-structure the more I think I'm
1006 ;; stupid. There has to be an easier way (but beware lots of code
1007 ;; depends on this).
1009 (defun yas--remove-template-by-uuid (table uuid)
1010 "Remove from TABLE a template identified by UUID."
1011 (let ((template (gethash uuid (yas--table-uuidhash table))))
1013 (let* ((name (yas--template-name template))
1015 ;; Remove the name from each of the targeted namehashes
1017 (maphash #'(lambda (k v)
1018 (let ((template (gethash name v)))
1020 (eq uuid (yas--template-uuid template)))
1022 (when (zerop (hash-table-count v))
1023 (push k empty-keys)))))
1024 (yas--table-hash table))
1025 ;; Remove the namehash themselves if they've become empty
1027 (dolist (key empty-keys)
1029 (define-key (yas--table-direct-keymap table) key nil))
1030 (remhash key (yas--table-hash table)))
1032 ;; Finally, remove the uuid from the uuidhash
1034 (remhash uuid (yas--table-uuidhash table))))))
1036 (defun yas--add-template (table template)
1037 "Store in TABLE the snippet template TEMPLATE.
1039 KEY can be a string (trigger key) of a vector (direct
1041 (let ((name (yas--template-name template))
1042 (key (yas--template-key template))
1043 (keybinding (yas--template-keybinding template))
1044 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1045 (dolist (k (remove nil (list key keybinding)))
1049 (yas--table-hash table))
1051 (make-hash-table :test 'equal)
1052 (yas--table-hash table))))
1054 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1056 ;; Update TABLE's `yas--table-uuidhash'
1057 (puthash (yas--template-uuid template)
1059 (yas--table-uuidhash table))))
1061 (defun yas--update-template (table template)
1062 "Add or update TEMPLATE in TABLE.
1064 Also takes care of adding and updating to the associated menu."
1065 ;; Remove from table by uuid
1067 (yas--remove-template-by-uuid table (yas--template-uuid template))
1068 ;; Add to table again
1070 (yas--add-template table template)
1071 ;; Take care of the menu
1074 (yas--update-template-menu table template)))
1076 (defun yas--update-template-menu (table template)
1077 "Update every menu-related for TEMPLATE."
1078 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1079 (key (yas--template-key template))
1080 (keybinding (yas--template-keybinding template)))
1081 ;; The snippet might have changed name or keys, so update
1082 ;; user-visible strings
1084 (unless (eq (cdr menu-binding-pair) :none)
1085 ;; the menu item name
1087 (setf (cadar menu-binding-pair) (yas--template-name template))
1088 ;; the :keys information (also visible to the user)
1089 (setf (getf (cdr (car menu-binding-pair)) :keys)
1090 (or (and keybinding (key-description keybinding))
1091 (and key (concat key yas-trigger-symbol))))))
1092 (unless (yas--template-menu-managed-by-yas-define-menu template)
1094 (yas--menu-keymap-get-create (yas--table-mode table)
1095 (mapcar #'yas--table-mode
1096 (yas--table-parents table))))
1097 (group (yas--template-group template)))
1098 ;; Remove from menu keymap
1100 (assert menu-keymap)
1101 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1103 ;; Add necessary subgroups as necessary.
1105 (dolist (subgroup group)
1106 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1107 (unless (and subgroup-keymap
1108 (keymapp subgroup-keymap))
1109 (setq subgroup-keymap (make-sparse-keymap))
1110 (define-key menu-keymap (vector (make-symbol subgroup))
1111 `(menu-item ,subgroup ,subgroup-keymap)))
1112 (setq menu-keymap subgroup-keymap)))
1114 ;; Add this entry to the keymap
1116 (define-key menu-keymap
1117 (vector (make-symbol (yas--template-uuid template)))
1118 (car (yas--template-menu-binding-pair template))))))
1120 (defun yas--namehash-templates-alist (namehash)
1121 "Return NAMEHASH as an alist."
1123 (maphash #'(lambda (k v)
1124 (push (cons k v) alist))
1128 (defun yas--fetch (table key)
1129 "Fetch templates in TABLE by KEY.
1131 Return a list of cons (NAME . TEMPLATE) where NAME is a
1132 string and TEMPLATE is a `yas--template' structure."
1133 (let* ((keyhash (yas--table-hash table))
1134 (namehash (and keyhash (gethash key keyhash))))
1136 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1139 ;;; Filtering/condition logic
1141 (defun yas--eval-condition (condition)
1148 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1152 (defun yas--filter-templates-by-condition (templates)
1153 "Filter the templates using the applicable condition.
1155 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1156 string and TEMPLATE is a `yas--template' structure.
1158 This function implements the rules described in
1159 `yas-buffer-local-condition'. See that variables documentation."
1160 (let ((requirement (yas--require-template-specific-condition-p)))
1161 (if (eq requirement 'always)
1163 (remove-if-not #'(lambda (pair)
1164 (yas--template-can-expand-p
1165 (yas--template-condition (cdr pair)) requirement))
1168 (defun yas--require-template-specific-condition-p ()
1169 "Decide if this buffer requests/requires snippet-specific
1170 conditions to filter out potential expansions."
1171 (if (eq 'always yas-buffer-local-condition)
1173 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1174 (yas--eval-condition yas-buffer-local-condition))
1175 yas-buffer-local-condition)))
1176 (when local-condition
1177 (if (eq local-condition t)
1179 (and (consp local-condition)
1180 (eq 'require-snippet-condition (car local-condition))
1181 (symbolp (cdr local-condition))
1182 (cdr local-condition)))))))
1184 (defun yas--template-can-expand-p (condition requirement)
1185 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1186 (let* ((result (or (null condition)
1187 (yas--eval-condition condition))))
1188 (cond ((eq requirement t)
1191 (eq requirement result)))))
1193 (defun yas--table-templates (table)
1196 (maphash #'(lambda (_key namehash)
1197 (maphash #'(lambda (name template)
1198 (push (cons name template) acc))
1200 (yas--table-hash table))
1201 (yas--filter-templates-by-condition acc))))
1203 (defun yas--current-key ()
1204 "Get the key under current position.
1205 A key is used to find the template of a snippet in the current snippet-table."
1206 (let ((start (point))
1208 (syntaxes yas-key-syntaxes)
1212 (while (and (not done) syntaxes)
1213 (setq syntax (car syntaxes))
1214 (setq syntaxes (cdr syntaxes))
1216 (skip-syntax-backward syntax)
1217 (setq start (point)))
1219 (mapcan #'(lambda (table)
1220 (yas--fetch table (buffer-substring-no-properties start end)))
1221 (yas--get-snippet-tables)))
1230 (defun yas--table-all-keys (table)
1231 "Get trigger keys of all active snippets in TABLE."
1233 (maphash #'(lambda (key namehash)
1234 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1236 (yas--table-hash table))
1239 (defun yas--table-mode (table)
1240 (intern (yas--table-name table)))
1243 ;;; Internal functions and macros:
1245 (defun yas--real-mode? (mode)
1246 "Try to find out if MODE is a real mode.
1248 The MODE bound to a function (like `c-mode') is considered real
1249 mode. Other well known mode like `ruby-mode' which is not part of
1250 Emacs might not bound to a function until it is loaded. So
1251 yasnippet keeps a list of modes like this to help the judgment."
1253 (find mode yas--known-modes)))
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 (if yas-good-grace
1267 (yas--format "elisp error! %s" (error-message-string err))
1268 (error (yas--format "elisp error: %s"
1269 (error-message-string err)))))))))
1270 (when (and (consp retval)
1271 (eq 'yas--exception (car retval)))
1272 (error (cdr retval)))
1275 (defun yas--eval-lisp-no-saves (form)
1278 (error (if yas-good-grace
1279 (yas--format "elisp error! %s" (error-message-string err))
1280 (error (yas--format "elisp error: %s"
1281 (error-message-string err)))))))
1283 (defun yas--read-lisp (string &optional nil-on-error)
1284 "Read STRING as a elisp expression and return it.
1286 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1287 return an expression that when evaluated will issue an error."
1290 (error (and (not nil-on-error)
1291 `(error (error-message-string ,err))))))
1293 (defun yas--read-keybinding (keybinding)
1294 "Read KEYBINDING as a snippet keybinding, return a vector."
1295 (when (and keybinding
1296 (not (string-match "keybinding" keybinding)))
1298 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1300 (read-kbd-macro keybinding 'need-vector))))
1303 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1304 keybinding (error-message-string err))
1307 (defun yas--table-get-create (mode)
1308 "Get or create the snippet table corresponding to MODE."
1309 (let ((table (gethash mode
1312 (setq table (yas--make-snippet-table (symbol-name mode)))
1313 (puthash mode table yas--tables)
1314 (push (cons (intern (format "yas--direct-%s" mode))
1315 (yas--table-direct-keymap table))
1316 yas--direct-keymaps))
1319 (defun yas--get-snippet-tables ()
1320 "Get snippet tables for current buffer.
1322 Return a list of `yas--table' objects. The list of modes to
1323 consider is returned by `yas--modes-to-activate'"
1325 (mapcar #'(lambda (name)
1326 (gethash name yas--tables))
1327 (yas--modes-to-activate))))
1329 (defun yas--menu-keymap-get-create (mode &optional parents)
1330 "Get or create the menu keymap for MODE and its PARENTS.
1332 This may very well create a plethora of menu keymaps and arrange
1333 them all in `yas--menu-table'"
1334 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1335 (puthash mode (make-sparse-keymap) yas--menu-table))))
1336 (mapc #'yas--menu-keymap-get-create parents)
1337 (define-key yas--minor-mode-menu (vector mode)
1338 `(menu-item ,(symbol-name mode) ,menu-keymap
1339 :visible (yas--show-menu-p ',mode)))
1343 (defmacro yas--called-interactively-p (&optional kind)
1344 "A backward-compatible version of `called-interactively-p'.
1346 Optional KIND is as documented at `called-interactively-p'
1347 in GNU Emacs 24.1 or higher."
1348 (if (string< emacs-version "24.1")
1349 '(called-interactively-p)
1350 `(called-interactively-p ,kind)))
1353 ;;; Template-related and snippet loading functions
1355 (defun yas--parse-template (&optional file)
1356 "Parse the template in the current buffer.
1358 Optional FILE is the absolute file name of the file being
1361 Optional GROUP is the group where the template is to go,
1362 otherwise we attempt to calculate it from FILE.
1364 Return a snippet-definition, i.e. a list
1366 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1368 If the buffer contains a line of \"# --\" then the contents above
1369 this line are ignored. Directives can set most of these with the syntax:
1371 # directive-name : directive-value
1373 Here's a list of currently recognized directives:
1384 (goto-char (point-min))
1385 (let* ((type 'snippet)
1387 (file-name-nondirectory file)))
1393 (yas--calculate-group file)))
1397 (if (re-search-forward "^# --\n" nil t)
1398 (progn (setq template
1399 (buffer-substring-no-properties (point)
1401 (setq bound (point))
1402 (goto-char (point-min))
1403 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1404 (when (string= "uuid" (match-string-no-properties 1))
1405 (setq uuid (match-string-no-properties 2)))
1406 (when (string= "type" (match-string-no-properties 1))
1407 (setq type (if (string= "command" (match-string-no-properties 2))
1410 (when (string= "key" (match-string-no-properties 1))
1411 (setq key (match-string-no-properties 2)))
1412 (when (string= "name" (match-string-no-properties 1))
1413 (setq name (match-string-no-properties 2)))
1414 (when (string= "condition" (match-string-no-properties 1))
1415 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1416 (when (string= "group" (match-string-no-properties 1))
1417 (setq group (match-string-no-properties 2)))
1418 (when (string= "expand-env" (match-string-no-properties 1))
1419 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1421 (when (string= "binding" (match-string-no-properties 1))
1422 (setq binding (match-string-no-properties 2)))))
1424 (buffer-substring-no-properties (point-min) (point-max))))
1425 (unless (or key binding)
1426 (setq key (and file (file-name-nondirectory file))))
1427 (when (eq type 'command)
1428 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1430 (setq group (split-string group "\\.")))
1431 (list key template name condition group expand-env file binding uuid)))
1433 (defun yas--calculate-group (file)
1434 "Calculate the group for snippet file path FILE."
1435 (let* ((dominating-dir (locate-dominating-file file
1436 ".yas-make-groups"))
1437 (extra-path (and dominating-dir
1438 (replace-regexp-in-string (concat "^"
1439 (expand-file-name dominating-dir))
1441 (expand-file-name file))))
1442 (extra-dir (and extra-path
1443 (file-name-directory extra-path)))
1444 (group (and extra-dir
1445 (replace-regexp-in-string "/"
1447 (directory-file-name extra-dir)))))
1450 (defun yas--subdirs (directory &optional filep)
1451 "Return subdirs or files of DIRECTORY according to FILEP."
1452 (remove-if (lambda (file)
1453 (or (string-match "^\\."
1454 (file-name-nondirectory file))
1455 (string-match "^#.*#$"
1456 (file-name-nondirectory file))
1458 (file-name-nondirectory file))
1460 (file-directory-p file)
1461 (not (file-directory-p file)))))
1462 (directory-files directory t)))
1464 (defun yas--make-menu-binding (template)
1465 (let ((mode (yas--table-mode (yas--template-table template))))
1466 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1468 (defun yas--expand-or-visit-from-menu (mode uuid)
1469 (let* ((table (yas--table-get-create mode))
1470 (yas--current-template (and table
1471 (gethash uuid (yas--table-uuidhash table)))))
1472 (when yas--current-template
1473 (if yas-visit-from-menu
1474 (yas--visit-snippet-file-1 yas--current-template)
1475 (let ((where (if (region-active-p)
1476 (cons (region-beginning) (region-end))
1477 (cons (point) (point)))))
1478 (yas-expand-snippet (yas--template-content yas--current-template)
1481 (yas--template-expand-env yas--current-template)))))))
1483 (defun yas--key-from-desc (text)
1484 "Return a yasnippet key from a description string TEXT."
1485 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1488 ;;; Popping up for keys and templates
1490 (defvar yas--x-pretty-prompt-templates nil
1491 "If non-nil, attempt to prompt for templates like TextMate.")
1494 (defun yas--prompt-for-template (templates &optional prompt)
1495 "Interactively choose a template from the list TEMPLATES.
1497 TEMPLATES is a list of `yas--template'.
1499 Optional PROMPT sets the prompt to use."
1502 (sort templates #'(lambda (t1 t2)
1503 (< (length (yas--template-name t1))
1504 (length (yas--template-name t2))))))
1505 (if yas--x-pretty-prompt-templates
1506 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1507 (some #'(lambda (fn)
1508 (funcall fn (or prompt "Choose a snippet: ")
1510 #'yas--template-name))
1511 yas-prompt-functions))))
1513 (defun yas--prompt-for-keys (keys &optional prompt)
1514 "Interactively choose a template key from the list KEYS.
1516 Optional PROMPT sets the prompt to use."
1518 (some #'(lambda (fn)
1519 (funcall fn (or prompt "Choose a snippet key: ") keys))
1520 yas-prompt-functions)))
1522 (defun yas--prompt-for-table (tables &optional prompt)
1523 "Interactively choose a table from the list TABLES.
1525 Optional PROMPT sets the prompt to use."
1527 (some #'(lambda (fn)
1528 (funcall fn (or prompt "Choose a snippet table: ")
1531 yas-prompt-functions)))
1533 (defun yas-x-prompt (prompt choices &optional display-fn)
1534 "Display choices in a x-window prompt."
1535 ;; FIXME: HACK: if we notice that one of the objects in choices is
1536 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1538 ;; This would be better implemented by passing CHOICES as a
1539 ;; structured tree rather than a list. Modifications would go as far
1540 ;; up as `yas--all-templates' I think.
1542 (when (and window-system choices)
1544 (let (menu d) ;; d for display
1546 (setq d (or (and display-fn (funcall display-fn c))
1549 (push (cons (concat " " d) c) menu))
1551 (push (car d) menu))))
1552 (setq menu (list prompt (push "title" menu)))
1553 (x-popup-menu (if (fboundp 'posn-at-point)
1554 (let ((x-y (posn-x-y (posn-at-point (point)))))
1555 (list (list (+ (car x-y) 10)
1563 (defun yas--x-pretty-prompt-templates (prompt templates)
1564 "Display TEMPLATES, grouping neatly by table name."
1565 (let ((organized (make-hash-table :test #'equal))
1569 (dolist (tl templates)
1570 (puthash (yas--template-table tl)
1572 (gethash (yas--template-table tl) organized))
1574 (setq more-than-one-table (> (hash-table-count organized) 1))
1575 (setq prefix (if more-than-one-table
1577 (if more-than-one-table
1578 (maphash #'(lambda (table templates)
1579 (push (yas--table-name table) menu)
1580 (dolist (tl templates)
1581 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1582 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1584 (setq menu (nreverse menu))
1585 (or (x-popup-menu (if (fboundp 'posn-at-point)
1586 (let ((x-y (posn-x-y (posn-at-point (point)))))
1587 (list (list (+ (car x-y) 10)
1591 (list prompt (push "title" menu)))
1594 (defun yas-ido-prompt (prompt choices &optional display-fn)
1595 (when (and (fboundp 'ido-completing-read)
1596 (or (>= emacs-major-version 24)
1598 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1600 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1601 (when (fboundp 'dropdown-list)
1602 (let (formatted-choices
1606 (dolist (choice choices)
1607 (setq d (or (and display-fn (funcall display-fn choice))
1610 (push d formatted-choices)
1611 (push choice filtered-choices)))
1613 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1615 (nth n filtered-choices)
1618 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1619 (let (formatted-choices
1623 (completion-fn (or completion-fn
1624 #'completing-read)))
1625 (dolist (choice choices)
1626 (setq d (or (and display-fn (funcall display-fn choice))
1629 (push d formatted-choices)
1630 (push choice filtered-choices)))
1631 (setq chosen (and formatted-choices
1632 (funcall completion-fn prompt
1638 (let ((position (or (and chosen
1639 (position chosen formatted-choices :test #'string=))
1641 (nth position filtered-choices))))
1643 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1647 ;;; Defining snippets
1648 ;; This consists of creating and registering `yas--template' objects in the
1652 (defvar yas--creating-compiled-snippets nil)
1654 (defun yas--define-snippets-1 (snippet snippet-table)
1655 "Helper for `yas-define-snippets'."
1656 ;; X) Calculate some more defaults on the values returned by
1657 ;; `yas--parse-template'.
1659 (let* ((file (seventh snippet))
1661 (name (or (third snippet)
1663 (file-name-directory file))))
1664 (condition (fourth snippet))
1665 (group (fifth snippet))
1666 (keybinding (yas--read-keybinding (eighth snippet)))
1667 (uuid (or (ninth snippet)
1669 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1670 (yas--make-blank-template))))
1671 ;; X) populate the template object
1673 (yas--populate-template template
1674 :table snippet-table
1676 :content (second snippet)
1679 :condition condition
1680 :expand-env (sixth snippet)
1681 :file (seventh snippet)
1682 :keybinding keybinding
1684 ;; X) Update this template in the appropriate table. This step
1685 ;; also will take care of adding the key indicators in the
1686 ;; templates menu entry, if any
1688 (yas--update-template snippet-table template)
1689 ;; X) Return the template
1694 (defun yas-define-snippets (mode snippets)
1695 "Define SNIPPETS for MODE.
1697 SNIPPETS is a list of snippet definitions, each taking the
1700 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1702 Within these, only KEY and TEMPLATE are actually mandatory.
1704 TEMPLATE might be a Lisp form or a string, depending on whether
1705 this is a snippet or a snippet-command.
1707 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1708 been `yas--read-lisp'-ed and will eventually be
1709 `yas--eval-lisp'-ed.
1711 The remaining elements are strings.
1713 FILE is probably of very little use if you're programatically
1716 UUID is the snippets \"unique-id\". Loading a second snippet file
1717 with the same uuid replaced the previous snippet.
1719 You can use `yas--parse-template' to return such lists based on
1720 the current buffers contents."
1721 (if yas--creating-compiled-snippets
1723 (insert ";;; Snippet definitions:\n;;;\n")
1724 (let ((literal-snippets (list))
1726 (dolist (snippet snippets)
1727 (let ((key (nth 0 snippet))
1728 (template-content (nth 1 snippet))
1729 (name (nth 2 snippet))
1730 (condition (nth 3 snippet))
1731 (group (nth 4 snippet))
1732 (expand-env (nth 5 snippet))
1733 (file nil) ;; omit on purpose
1734 (binding (nth 7 snippet))
1735 (uuid (nth 8 snippet)))
1746 (insert (pp-to-string
1747 `(yas-define-snippets ',mode ',literal-snippets)))
1750 (let ((snippet-table (yas--table-get-create mode))
1752 (dolist (snippet snippets)
1753 (setq template (yas--define-snippets-1 snippet
1758 ;;; Loading snippets from files
1760 (defun yas--load-yas-setup-file (file)
1761 (if (not yas--creating-compiled-snippets)
1763 (load file 'noerror)
1764 (let ((elfile (concat file ".el")))
1765 (when (file-exists-p elfile)
1766 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1767 (insert-file-contents elfile)
1768 (goto-char (point-max))))))
1770 (defun yas--define-parents (mode parents)
1771 "Add PARENTS to the list of MODE's parents."
1772 (puthash mode (remove-duplicates
1774 (gethash mode yas--parents)))
1777 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1778 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1780 Below TOP-LEVEL-DIR each directory should be a mode name.
1782 Optional USE-JIT use jit-loading of snippets."
1783 (interactive "DSelect the root directory: ni\np")
1784 (unless yas-snippet-dirs
1785 (setq yas-snippet-dirs top-level-dir))
1786 (dolist (dir (yas--subdirs top-level-dir))
1787 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1788 (concat dir "/dummy")))
1789 (mode-sym (car major-mode-and-parents))
1790 (parents (cdr major-mode-and-parents)))
1791 ;; Attention: The parents and the menus are already defined
1792 ;; here, even if the snippets are later jit-loaded.
1794 ;; * We need to know the parents at this point since entering a
1795 ;; given mode should jit load for its parents
1796 ;; immediately. This could be reviewed, the parents could be
1797 ;; discovered just-in-time-as well
1799 ;; * We need to create the menus here to support the `full'
1800 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1802 (yas--define-parents mode-sym parents)
1803 (yas--menu-keymap-get-create mode-sym)
1804 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1805 (yas--load-directory-1 ',dir ',mode-sym))))
1807 (not (some #'(lambda (buffer)
1808 (with-current-buffer buffer
1809 ;; FIXME: Shouldn't this use derived-mode-p?
1810 (when (eq major-mode mode-sym)
1811 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1814 (yas--schedule-jit mode-sym fun)
1817 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1819 (defun yas--load-directory-1 (directory mode-sym)
1820 "Recursively load snippet templates from DIRECTORY."
1821 (if yas--creating-compiled-snippets
1822 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1824 (with-temp-file output-file
1825 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1827 (yas--load-directory-2 directory mode-sym)
1828 (insert (format ";;; Do not edit! File generated at %s\n"
1829 (current-time-string)))))
1831 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1832 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1833 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1834 (yas--message 2 "Loading snippet files from %s" directory)
1835 (yas--load-directory-2 directory mode-sym)))))
1837 (defun yas--load-directory-2 (directory mode-sym)
1838 ;; Load .yas-setup.el files wherever we find them
1840 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1841 (let* ((default-directory directory)
1843 ;; load the snippet files
1846 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1847 (when (file-readable-p file)
1848 (insert-file-contents file nil nil nil t)
1849 (push (yas--parse-template file)
1852 (yas-define-snippets mode-sym
1854 ;; now recurse to a lower level
1856 (dolist (subdir (yas--subdirs directory))
1857 (yas--load-directory-2 subdir
1860 (defun yas--load-snippet-dirs (&optional nojit)
1861 "Reload the directories listed in `yas-snippet-dirs' or
1862 prompt the user to select one."
1864 (if yas-snippet-dirs
1865 (dolist (directory (reverse (yas-snippet-dirs)))
1866 (cond ((file-directory-p directory)
1867 (yas-load-directory directory (not nojit))
1869 (yas--message 3 "Loaded %s" directory)
1870 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1872 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1873 (call-interactively 'yas-load-directory))
1876 (defun yas-reload-all (&optional interactive)
1877 "Reload all snippets and rebuild the YASnippet menu.
1879 When called interactively force immediate reload of all known
1880 snippets under `yas-snippet-dirs', otherwise use just-in-time
1885 (snippet-editing-buffers
1886 (remove-if-not #'(lambda (buffer)
1887 (with-current-buffer buffer yas--editing-template))
1889 ;; Warn if there are buffers visiting snippets, since reloading will break
1890 ;; any on-line editing of those buffers.
1892 (when snippet-editing-buffers
1894 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1895 (mapc #'kill-buffer snippet-editing-buffers)
1896 (yas--message 1 "Aborted reload...")
1898 ;; in a non-interactive use, at least set
1899 ;; `yas--editing-template' to nil, make it guess it next time around
1900 (mapc #'(lambda (buffer)
1901 (with-current-buffer buffer
1902 (kill-local-variable 'yas--editing-template)))
1905 ;; Empty all snippet tables and parenting info
1907 (setq yas--tables (make-hash-table))
1908 (setq yas--parents (make-hash-table))
1910 ;; Before killing `yas--menu-table' use its keys to cleanup the
1911 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1912 ;; up `yas-minor-mode-map', which points to it)
1914 (maphash #'(lambda (menu-symbol _keymap)
1915 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1917 ;; Now empty `yas--menu-table' as well
1918 (setq yas--menu-table (make-hash-table))
1920 ;; Cancel all pending 'yas--scheduled-jit-loads'
1922 (setq yas--scheduled-jit-loads (make-hash-table))
1924 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1925 ;; the user to select one.
1927 (setq errors (yas--load-snippet-dirs interactive))
1928 ;; Reload the direct keybindings
1930 (yas-direct-keymaps-reload)
1932 (yas--message 3 "Reloaded everything%s...%s."
1933 (if interactive "" " (snippets will load just-in-time)")
1934 (if errors " (some errors, check *Messages*)" "")))))
1936 (defun yas--load-pending-jits ()
1937 (dolist (mode (yas--modes-to-activate))
1938 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1939 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1941 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1943 (remhash mode yas--scheduled-jit-loads))))
1945 ;; (when (<= emacs-major-version 22)
1946 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1948 (defun yas--quote-string (string)
1949 "Escape and quote STRING.
1950 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1952 (replace-regexp-in-string "[\\\"]"
1958 ;;; Snippet compilation function
1960 (defun yas--initialize ()
1961 "For backward compatibility, enable `yas-minor-mode' globally."
1962 (yas-global-mode 1))
1964 (defun yas-compile-directory (top-level-dir)
1965 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1967 This works by stubbing a few functions, then calling
1968 `yas-load-directory'."
1969 (interactive "DTop level snippet directory?")
1970 (let ((yas--creating-compiled-snippets t))
1971 (yas-load-directory top-level-dir nil)))
1973 (defun yas-recompile-all ()
1974 "Compile every dir in `yas-snippet-dirs'."
1976 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1982 (defvar yas--scheduled-jit-loads (make-hash-table)
1983 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1985 (defun yas--schedule-jit (mode fun)
1986 (push fun (gethash mode yas--scheduled-jit-loads)))
1990 ;;; Some user level functions
1994 (message (concat "yasnippet (version "
1996 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1999 ;;; Apropos snippet menu:
2001 ;; The snippet menu keymaps are store by mode in hash table called
2002 ;; `yas--menu-table'. They are linked to the main menu in
2003 ;; `yas--menu-keymap-get-create' and are initially created empty,
2004 ;; reflecting the table hierarchy.
2006 ;; They can be populated in two mutually exclusive ways: (1) by
2007 ;; reading `yas--template-group', which in turn is populated by the "#
2008 ;; group:" directives of the snippets or the ".yas-make-groups" file
2009 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2010 ;; menu structure based on snippets uuids.
2012 ;; Both situations are handled in `yas--update-template-menu', which
2013 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2014 ;; that can tell between the two situations.
2018 ;; * if `yas-define-menu' is used it must run before
2019 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2020 ;; duplicate entries. The `yas--template' objects are created in
2021 ;; `yas-define-menu', holding nothing but the menu entry,
2022 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2023 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2024 ;; part is then stored in the menu keymap itself which make the item
2025 ;; appear to the user. These limitations could probably be revised.
2027 ;; * The `yas--template-perm-group' slot is only used in
2028 ;; `yas-describe-tables'.
2030 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2031 "Get TEMPLATE's menu binding or assign it a new one.
2033 TYPE may be `:stay', signaling this menu binding should be
2034 static in the menu."
2035 (or (yas--template-menu-binding-pair template)
2036 (let (;; (key (yas--template-key template))
2037 ;; (keybinding (yas--template-keybinding template))
2039 (setf (yas--template-menu-binding-pair template)
2040 (cons `(menu-item ,(or (yas--template-name template)
2041 (yas--template-uuid template))
2042 ,(yas--make-menu-binding template)
2045 (defun yas--template-menu-managed-by-yas-define-menu (template)
2046 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2047 (cdr (yas--template-menu-binding-pair template)))
2050 (defun yas--show-menu-p (mode)
2051 (cond ((eq yas-use-menu 'abbreviate)
2053 (mapcar #'(lambda (table)
2054 (yas--table-mode table))
2055 (yas--get-snippet-tables))))
2056 ((eq yas-use-menu 'full)
2058 ((eq yas-use-menu t)
2061 (defun yas--delete-from-keymap (keymap uuid)
2062 "Recursively delete items with UUID from KEYMAP and its submenus."
2064 ;; XXX: This used to skip any submenus named \"parent mode\"
2066 ;; First of all, recursively enter submenus, i.e. the tree is
2067 ;; searched depth first so that stale submenus can be found in the
2070 (mapc #'(lambda (item)
2071 (when (and (listp (cdr item))
2072 (keymapp (third (cdr item))))
2073 (yas--delete-from-keymap (third (cdr item)) uuid)))
2075 ;; Set the uuid entry to nil
2077 (define-key keymap (vector (make-symbol uuid)) nil)
2078 ;; Destructively modify keymap
2080 (setcdr keymap (delete-if #'(lambda (item)
2081 (or (null (cdr item))
2082 (and (keymapp (third (cdr item)))
2083 (null (cdr (third (cdr item)))))))
2086 (defun yas-define-menu (mode menu &optional omit-items)
2087 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2089 MENU is a list, its elements can be:
2091 - (yas-item UUID) : Creates an entry the snippet identified with
2092 UUID. The menu entry for a snippet thus identified is
2093 permanent, i.e. it will never move (be reordered) in the menu.
2095 - (yas-separator) : Creates a separator
2097 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2098 SUBMENU has the same form as MENU. NAME is also added to the
2099 list of groups of the snippets defined thereafter.
2101 OMIT-ITEMS is a list of snippet uuid's that will always be
2102 omitted from MODE's menu, even if they're manually loaded.
2104 This function does nothing if `yas-use-menu' is nil."
2106 (let* ((table (yas--table-get-create mode))
2107 (hash (yas--table-uuidhash table)))
2108 (yas--define-menu-1 table
2109 (yas--menu-keymap-get-create mode)
2112 (dolist (uuid omit-items)
2113 (let ((template (or (gethash uuid hash)
2114 (yas--populate-template (puthash uuid
2115 (yas--make-blank-template)
2119 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2121 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2122 "Helper for `yas-define-menu'."
2123 (dolist (e (reverse menu))
2124 (cond ((eq (first e) 'yas-item)
2125 (let ((template (or (gethash (second e) uuidhash)
2126 (yas--populate-template (puthash (second e)
2127 (yas--make-blank-template)
2130 :perm-group group-list
2131 :uuid (second e)))))
2132 (define-key menu-keymap (vector (gensym))
2133 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2134 ((eq (first e) 'yas-submenu)
2135 (let ((subkeymap (make-sparse-keymap)))
2136 (define-key menu-keymap (vector (gensym))
2137 `(menu-item ,(second e) ,subkeymap))
2138 (yas--define-menu-1 table
2142 (append group-list (list (second e))))))
2143 ((eq (first e) 'yas-separator)
2144 (define-key menu-keymap (vector (gensym))
2145 '(menu-item "----")))
2147 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2149 (defun yas--define (mode key template &optional name condition group)
2150 "Define a snippet. Expanding KEY into TEMPLATE.
2152 NAME is a description to this template. Also update the menu if
2153 `yas-use-menu' is t. CONDITION is the condition attached to
2154 this snippet. If you attach a condition to a snippet, then it
2155 will only be expanded when the condition evaluated to non-nil."
2156 (yas-define-snippets mode
2157 (list (list key template name condition group))))
2159 (defun yas-hippie-try-expand (first-time?)
2160 "Integrate with hippie expand.
2162 Just put this function in `hippie-expand-try-functions-list'."
2163 (when yas-minor-mode
2164 (if (not first-time?)
2165 (let ((yas-fallback-behavior 'return-nil))
2171 ;;; Apropos condition-cache:
2176 (defvar yas--condition-cache-timestamp nil)
2177 (defmacro yas-define-condition-cache (func doc &rest body)
2178 "Define a function FUNC with doc DOC and body BODY.
2179 BODY is executed at most once every snippet expansion attempt, to check
2180 expansion conditions.
2182 It doesn't make any sense to call FUNC programatically."
2183 `(defun ,func () ,(if (and doc
2186 "\n\nFor use in snippets' conditions. Within each
2187 snippet-expansion routine like `yas-expand', computes actual
2188 value for the first time then always returns a cached value.")
2189 (setq body (cons doc body))
2191 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2192 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2193 (cdr timestamp-and-value)
2194 (let ((new-value (progn
2197 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2200 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2201 (defun yas-expand-from-trigger-key (&optional field)
2202 "Expand a snippet before point.
2204 If no snippet expansion is possible, fall back to the behaviour
2205 defined in `yas-fallback-behavior'.
2207 Optional argument FIELD is for non-interactive use and is an
2208 object satisfying `yas--field-p' to restrict the expansion to."
2210 (setq yas--condition-cache-timestamp (current-time))
2211 (let (templates-and-pos)
2212 (unless (and yas-expand-only-for-last-commands
2213 (not (member last-command yas-expand-only-for-last-commands)))
2214 (setq templates-and-pos (if field
2216 (narrow-to-region (yas--field-start field)
2217 (yas--field-end field))
2219 (yas--current-key))))
2220 (if (and templates-and-pos
2221 (first templates-and-pos))
2222 (yas--expand-or-prompt-for-template (first templates-and-pos)
2223 (second templates-and-pos)
2224 (third templates-and-pos))
2227 (defun yas-expand-from-keymap ()
2228 "Directly expand some snippets, searching `yas--direct-keymaps'.
2230 If expansion fails, execute the previous binding for this key"
2232 (setq yas--condition-cache-timestamp (current-time))
2233 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2234 (length (this-command-keys))
2236 (templates (mapcan #'(lambda (table)
2237 (yas--fetch table vec))
2238 (yas--get-snippet-tables))))
2240 (yas--expand-or-prompt-for-template templates)
2241 (let ((yas-fallback-behavior 'call-other-command))
2244 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2245 "Expand one of TEMPLATES from START to END.
2247 Prompt the user if TEMPLATES has more than one element, else
2248 expand immediately. Common gateway for
2249 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2250 (let ((yas--current-template (or (and (rest templates) ;; more than one
2251 (yas--prompt-for-template (mapcar #'cdr templates)))
2253 (when yas--current-template
2254 (yas-expand-snippet (yas--template-content yas--current-template)
2257 (yas--template-expand-env yas--current-template)))))
2259 ;; Apropos the trigger key and the fallback binding:
2261 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2262 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2263 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2264 ;; improve this explanation.
2266 (defun yas--fallback ()
2267 "Fallback after expansion has failed.
2269 Common gateway for `yas-expand-from-trigger-key' and
2270 `yas-expand-from-keymap'."
2271 (cond ((eq yas-fallback-behavior 'return-nil)
2274 ((eq yas-fallback-behavior 'call-other-command)
2275 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2276 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2277 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2278 (setq this-original-command beyond-yasnippet)
2279 (call-interactively beyond-yasnippet)))
2280 ((and (listp yas-fallback-behavior)
2281 (cdr yas-fallback-behavior)
2282 (eq 'apply (car yas-fallback-behavior)))
2283 (if (cddr yas-fallback-behavior)
2284 (apply (cadr yas-fallback-behavior)
2285 (cddr yas-fallback-behavior))
2286 (when (commandp (cadr yas-fallback-behavior))
2287 (setq this-command (cadr yas-fallback-behavior))
2288 (call-interactively (cadr yas-fallback-behavior)))))
2290 ;; also return nil if all the other fallbacks have failed
2293 (defun yas--keybinding-beyond-yasnippet ()
2295 (let* ((yas-minor-mode nil)
2296 (yas--direct-keymaps nil)
2297 (keys (this-single-command-keys)))
2298 (or (key-binding keys t)
2299 (key-binding (yas--fallback-translate-input keys) t))))
2301 (defun yas--fallback-translate-input (keys)
2302 "Emulate `read-key-sequence', at least what I think it does.
2304 Keys should be an untranslated key vector. Returns a translated
2305 vector of keys. FIXME not thoroughly tested."
2308 (while (< i (length keys))
2310 (translated local-function-key-map))
2311 (while (and (< j (length keys))
2313 (keymapp translated))
2314 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2316 (setq retval (vconcat retval (cond ((symbolp translated)
2318 ((vectorp translated)
2321 (substring keys i j)))))
2326 ;;; Utils for snippet development:
2328 (defun yas--all-templates (tables)
2329 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2331 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2332 `yas-buffer-local-condition'"
2333 (when yas-choose-tables-first
2334 (setq tables (list (yas--prompt-for-table tables))))
2336 (if yas-choose-keys-first
2337 (let ((key (yas--prompt-for-keys
2338 (mapcan #'yas--table-all-keys tables))))
2340 (mapcan #'(lambda (table)
2341 (yas--fetch table key))
2343 (remove-duplicates (mapcan #'yas--table-templates tables)
2346 (defun yas-insert-snippet (&optional no-condition)
2347 "Choose a snippet to expand, pop-up a list of choices according
2348 to `yas-prompt-functions'.
2350 With prefix argument NO-CONDITION, bypass filtering of snippets
2353 (setq yas--condition-cache-timestamp (current-time))
2354 (let* ((yas-buffer-local-condition (or (and no-condition
2356 yas-buffer-local-condition))
2357 (templates (yas--all-templates (yas--get-snippet-tables)))
2358 (yas--current-template (and templates
2359 (or (and (rest templates) ;; more than one template for same key
2360 (yas--prompt-for-template templates))
2362 (where (if (region-active-p)
2363 (cons (region-beginning) (region-end))
2364 (cons (point) (point)))))
2365 (if yas--current-template
2366 (yas-expand-snippet (yas--template-content yas--current-template)
2369 (yas--template-expand-env yas--current-template))
2370 (yas--message 3 "No snippets can be inserted here!"))))
2372 (defun yas-visit-snippet-file ()
2373 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2375 Only success if selected snippet was loaded from a file. Put the
2376 visited file in `snippet-mode'."
2378 (let* ((yas-buffer-local-condition 'always)
2379 (templates (yas--all-templates (yas--get-snippet-tables)))
2380 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2381 (template (and templates
2382 (or (yas--prompt-for-template templates
2383 "Choose a snippet template to edit: ")
2387 (yas--visit-snippet-file-1 template)
2388 (message "No snippets tables active!"))))
2390 (defun yas--visit-snippet-file-1 (template)
2391 "Helper for `yas-visit-snippet-file'."
2392 (let ((file (yas--template-file template)))
2393 (cond ((and file (file-readable-p file))
2394 (find-file-other-window file)
2396 (set (make-local-variable 'yas--editing-template) template))
2398 (message "Original file %s no longer exists!" file))
2400 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2401 (let ((type 'snippet))
2402 (when (listp (yas--template-content template))
2403 (insert (format "# type: command\n"))
2404 (setq type 'command))
2405 (insert (format "# key: %s\n" (yas--template-key template)))
2406 (insert (format "# name: %s\n" (yas--template-name template)))
2407 (when (yas--template-keybinding template)
2408 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2409 (when (yas--template-expand-env template)
2410 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2411 (when (yas--template-condition template)
2412 (insert (format "# condition: %s\n" (yas--template-condition template))))
2414 (insert (if (eq type 'command)
2415 (pp-to-string (yas--template-content template))
2416 (yas--template-content template))))
2418 (set (make-local-variable 'yas--editing-template) template)))))
2420 (defun yas--guess-snippet-directories-1 (table)
2421 "Guess possible snippet subdirectories for TABLE."
2422 (cons (yas--table-name table)
2423 (mapcan #'(lambda (parent)
2424 (yas--guess-snippet-directories-1
2426 (yas--table-parents table))))
2428 (defun yas--guess-snippet-directories (&optional table)
2429 "Try to guess suitable directories based on the current active
2430 tables (or optional TABLE).
2432 Returns a list of elements (TABLE . DIRS) where TABLE is a
2433 `yas--table' object and DIRS is a list of all possible directories
2434 where snippets of table might exist."
2435 (let ((main-dir (replace-regexp-in-string
2437 (or (first (or (yas-snippet-dirs)
2438 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2439 (tables (or (and table
2441 (yas--get-snippet-tables))))
2442 ;; HACK! the snippet table created here is actually registered!
2444 (unless (or table (gethash major-mode yas--tables))
2445 (push (yas--table-get-create major-mode)
2448 (mapcar #'(lambda (table)
2450 (mapcar #'(lambda (subdir)
2451 (concat main-dir "/" subdir))
2452 (yas--guess-snippet-directories-1 table))))
2455 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2456 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2457 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2458 (let ((candidate (first (cdr table-and-dirs))))
2459 (unless (file-writable-p (file-name-directory candidate))
2460 (error (yas--format "%s is not writable." candidate)))
2461 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2463 (if (gethash (yas--table-mode (car table-and-dirs))
2467 (or main-table-string
2469 (yas--table-name (car table-and-dirs))))
2471 (make-directory candidate 'also-make-parents)
2472 ;; create the .yas-parents file here...
2475 (defun yas-new-snippet (&optional no-template)
2476 "Pops a new buffer for writing a snippet.
2478 Expands a snippet-writing snippet, unless the optional prefix arg
2479 NO-TEMPLATE is non-nil."
2481 (let ((guessed-directories (yas--guess-snippet-directories)))
2483 (switch-to-buffer "*new snippet*")
2485 (kill-all-local-variables)
2488 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2489 (yas--table-mode (car d)))
2490 guessed-directories))
2491 (if (and (not no-template) yas-new-snippet-default)
2492 (yas-expand-snippet yas-new-snippet-default))))
2494 (defun yas--compute-major-mode-and-parents (file)
2495 "Given FILE, find the nearest snippet directory for a given mode.
2497 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2498 representing one or more of the mode's parents.
2500 Note that MODE-SYM need not be the symbol of a real major mode,
2501 neither do the elements of PARENTS."
2502 (let* ((file-dir (and file
2503 (directory-file-name (or (some #'(lambda (special)
2504 (locate-dominating-file file special))
2508 (directory-file-name (file-name-directory file))))))
2509 (parents-file-name (concat file-dir "/.yas-parents"))
2510 (major-mode-name (and file-dir
2511 (file-name-nondirectory file-dir)))
2512 (major-mode-sym (or (and major-mode-name
2513 (intern major-mode-name))))
2514 (parents (when (file-readable-p parents-file-name)
2518 (insert-file-contents parents-file-name)
2519 (buffer-substring-no-properties (point-min)
2521 (when major-mode-sym
2522 (cons major-mode-sym (remove major-mode-sym parents)))))
2524 (defvar yas--editing-template nil
2525 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2527 (defvar yas--current-template nil
2528 "Holds the current template being expanded into a snippet.")
2530 (defvar yas--guessed-modes nil
2531 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2533 (defun yas--read-table ()
2534 "Ask user for a snippet table, help with some guessing."
2535 (let ((prompt (if (and (featurep 'ido)
2537 'ido-completing-read 'completing-read)))
2538 (unless yas--guessed-modes
2539 (set (make-local-variable 'yas--guessed-modes)
2540 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2542 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2543 (if yas--guessed-modes
2544 (first yas--guessed-modes)
2546 (mapcar #'symbol-name yas--guessed-modes)
2551 (if (first yas--guessed-modes)
2552 (symbol-name (first yas--guessed-modes)))))))
2554 (defun yas-load-snippet-buffer (table &optional interactive)
2555 "Parse and load current buffer's snippet definition into TABLE.
2557 TABLE is a symbol naming a passed to `yas--table-get-create'.
2559 When called interactively, prompt for the table name."
2560 (interactive (list (yas--read-table) t))
2562 ;; We have `yas--editing-template', this buffer's content comes from a
2563 ;; template which is already loaded and neatly positioned,...
2565 (yas--editing-template
2566 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2567 (yas--template-table yas--editing-template)))
2568 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2569 ;; value from `yas--compute-major-mode-and-parents'
2572 (unless yas--guessed-modes
2573 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2574 (let* ((table (yas--table-get-create table)))
2575 (set (make-local-variable 'yas--editing-template)
2576 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2579 (yas--message 3 "Snippet \"%s\" loaded for %s."
2580 (yas--template-name yas--editing-template)
2581 (yas--table-name (yas--template-table yas--editing-template)))))
2583 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2584 "Load the snippet with `yas-load-snippet-buffer', possibly
2585 save, then `quit-window' if saved.
2587 If the snippet is new, ask the user whether (and where) to save
2588 it. If the snippet already has a file, just save it.
2590 The prefix argument KILL is passed to `quit-window'.
2592 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2593 and `kill-buffer' instead."
2594 (interactive (list (yas--read-table) current-prefix-arg))
2595 (yas-load-snippet-buffer table t)
2597 ;; Only offer to save this if it looks like a library or new
2598 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2599 ;; which is not the first, or from an unwritable file)
2601 (not (yas--template-file yas--editing-template))
2602 (not (file-writable-p (yas--template-file yas--editing-template)))
2603 (and (listp yas-snippet-dirs)
2604 (second yas-snippet-dirs)
2605 (not (string-match (expand-file-name (first yas-snippet-dirs))
2606 (yas--template-file yas--editing-template)))))
2607 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2608 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2610 (yas--make-directory-maybe option))))
2612 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2613 (file-name-nondirectory (yas--template-file yas--editing-template)))
2614 (yas--template-name yas--editing-template))))
2615 (write-file (concat chosen "/"
2616 (read-from-minibuffer (format "File name to create in %s? " chosen)
2617 default-file-name)))
2618 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2619 (when buffer-file-name
2621 (quit-window kill)))
2623 (defun yas-tryout-snippet (&optional debug)
2624 "Test current buffer's snippet template in other buffer."
2626 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2627 (parsed (yas--parse-template))
2628 (test-mode (or (and (car major-mode-and-parent)
2629 (fboundp (car major-mode-and-parent))
2630 (car major-mode-and-parent))
2631 (first yas--guessed-modes)
2632 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2633 (yas--current-template
2636 (yas--populate-template (yas--make-blank-template)
2637 :table nil ;; no tables for ephemeral snippets
2639 :content (second parsed)
2640 :name (third parsed)
2641 :expand-env (sixth parsed)))))
2642 (cond (yas--current-template
2643 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2644 (kill-buffer (get-buffer-create buffer-name))
2645 (switch-to-buffer (get-buffer-create buffer-name))
2646 (setq buffer-undo-list nil)
2647 (condition-case nil (funcall test-mode) (error nil))
2649 (setq buffer-read-only nil)
2650 (yas-expand-snippet (yas--template-content yas--current-template)
2653 (yas--template-expand-env yas--current-template))
2655 (require 'yasnippet-debug nil t))
2656 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2658 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2660 (defun yas-active-keys ()
2661 "Return all active trigger keys for current buffer and point."
2663 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2666 (defun yas--template-fine-group (template)
2667 (car (last (or (yas--template-group template)
2668 (yas--template-perm-group template)))))
2670 (defun yas-describe-tables (&optional choose)
2671 "Display snippets for each table."
2673 (let* ((by-name-hash (and choose
2674 (y-or-n-p "Show by namehash? ")))
2675 (buffer (get-buffer-create "*YASnippet tables*"))
2676 (active-tables (yas--get-snippet-tables))
2677 (remain-tables (let ((all))
2678 (maphash #'(lambda (_k v)
2679 (unless (find v active-tables)
2683 (table-lists (list active-tables remain-tables))
2684 (original-buffer (current-buffer))
2686 (yas--condition-cache-timestamp (current-time)))
2687 (with-current-buffer buffer
2688 (setq buffer-read-only nil)
2690 (cond ((not by-name-hash)
2691 (insert "YASnippet tables: \n")
2692 (while (and table-lists
2694 (dolist (table (car table-lists))
2695 (yas--describe-pretty-table table original-buffer))
2696 (setq table-lists (cdr table-lists))
2698 (yas--create-snippet-xrefs)
2699 (display-buffer buffer)
2700 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2701 (yas--create-snippet-xrefs)
2705 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2706 (dolist (table (append active-tables remain-tables))
2707 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2709 (maphash #'(lambda (k _v)
2711 (yas--table-hash table))
2713 (insert (format " key %s maps snippets: %s\n" key
2715 (maphash #'(lambda (k _v)
2717 (gethash key (yas--table-hash table)))
2720 (setq buffer-read-only t))
2721 (display-buffer buffer)))
2723 (defun yas--describe-pretty-table (table &optional original-buffer)
2724 (insert (format "\nSnippet table `%s'"
2725 (yas--table-name table)))
2726 (if (yas--table-parents table)
2727 (insert (format " parents: %s\n"
2728 (mapcar #'yas--table-name
2729 (yas--table-parents table))))
2731 (insert (make-string 100 ?-) "\n")
2732 (insert "group state name key binding\n")
2733 (let ((groups-hash (make-hash-table :test #'equal)))
2734 (maphash #'(lambda (_k v)
2735 (let ((group (or (yas--template-fine-group v)
2737 (when (yas--template-name v)
2739 (cons v (gethash group groups-hash))
2741 (yas--table-uuidhash table))
2743 #'(lambda (group templates)
2744 (setq group (truncate-string-to-width group 25 0 ? "..."))
2745 (insert (make-string 100 ?-) "\n")
2746 (dolist (p templates)
2747 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2751 (setq group (make-string (length group) ? ))))
2752 (condition-string (let ((condition (yas--template-condition p)))
2755 (with-current-buffer original-buffer
2756 (if (yas--eval-condition condition)
2761 (insert condition-string " ")
2763 (if (string-match "\\.\\.\\.$" name)
2767 (insert (truncate-string-to-width (or (yas--template-key p) "")
2769 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2776 ;;; User convenience functions, for using in snippet definitions
2778 (defvar yas-modified-p nil
2779 "Non-nil if field has been modified by user or transformation.")
2781 (defvar yas-moving-away-p nil
2782 "Non-nil if user is about to exit field.")
2784 (defvar yas-text nil
2785 "Contains current field text.")
2787 (defun yas-substr (str pattern &optional subexp)
2788 "Search PATTERN in STR and return SUBEXPth match.
2790 If found, the content of subexp group SUBEXP (default 0) is
2791 returned, or else the original STR will be returned."
2792 (let ((grp (or subexp 0)))
2794 (if (string-match pattern str)
2795 (match-string-no-properties grp str)
2798 (defun yas-choose-value (&rest possibilities)
2799 "Prompt for a string in POSSIBILITIES and return it.
2801 The last element of POSSIBILITIES may be a list of strings."
2802 (unless (or yas-moving-away-p
2804 (setq possibilities (nreverse possibilities))
2805 (setq possibilities (if (listp (car possibilities))
2806 (append (reverse (car possibilities)) (rest possibilities))
2808 (some #'(lambda (fn)
2809 (funcall fn "Choose: " possibilities))
2810 yas-prompt-functions)))
2812 (defun yas-key-to-value (alist)
2813 (unless (or yas-moving-away-p
2815 (let ((key (read-key-sequence "")))
2817 (or (cdr (find key alist :key #'car :test #'string=))
2820 (defun yas-throw (text)
2821 "Throw a yas--exception with TEXT as the reason."
2822 (throw 'yas--exception (cons 'yas--exception text)))
2824 (defun yas-verify-value (possibilities)
2825 "Verify that the current field value is in POSSIBILITIES.
2827 Otherwise throw exception."
2828 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2829 (yas-throw (yas--format "Field only allows %s" possibilities))))
2831 (defun yas-field-value (number)
2832 "Get the string for field with NUMBER.
2834 Use this in primary and mirror transformations to tget."
2835 (let* ((snippet (car (yas--snippets-at-point)))
2837 (yas--snippet-find-field snippet number))))
2839 (yas--field-text-for-display field))))
2842 "Return `yas-text' if that exists and is non-empty, else nil."
2844 (not (string= "" yas-text)))
2847 (defun yas-selected-text ()
2848 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2849 (if (and yas-selected-text
2850 (not (string= "" yas-selected-text)))
2853 (defun yas--get-field-once (number &optional transform-fn)
2854 (unless yas-modified-p
2856 (funcall transform-fn (yas-field-value number))
2857 (yas-field-value number))))
2859 (defun yas-default-from-field (number)
2860 (unless yas-modified-p
2861 (yas-field-value number)))
2863 (defun yas-inside-string ()
2864 "Return non-nil if the point is inside a string according to font-lock."
2865 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2867 (defun yas-unimplemented (&optional missing-feature)
2868 (if yas--current-template
2869 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2872 (yas--visit-snippet-file-1 yas--current-template))
2873 (message "No implementation. Missing %s" (or missing-feature "something"))))
2876 ;;; Snippet expansion and field management
2878 (defvar yas--active-field-overlay nil
2879 "Overlays the currently active field.")
2881 (defvar yas--field-protection-overlays nil
2882 "Two overlays protect the current active field.")
2884 (defvar yas-selected-text nil
2885 "The selected region deleted on the last snippet expansion.")
2887 (defvar yas--start-column nil
2888 "The column where the snippet expansion started.")
2890 (make-variable-buffer-local 'yas--active-field-overlay)
2891 (make-variable-buffer-local 'yas--field-protection-overlays)
2892 (put 'yas--active-field-overlay 'permanent-local t)
2893 (put 'yas--field-protection-overlays 'permanent-local t)
2895 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2901 (id (yas--snippet-next-id) :read-only t)
2902 (control-overlay nil)
2904 ;; stacked expansion: the `previous-active-field' slot saves the
2905 ;; active field where the child expansion took place
2906 previous-active-field
2909 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2912 NUMBER is the field number.
2913 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2914 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2915 MIRRORS is a list of `yas--mirror's
2916 TRANSFORM is a lisp form.
2917 MODIFIED-P is a boolean set to true once user inputs text.
2918 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2929 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2932 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2933 TRANSFORM is a lisp form.
2934 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2935 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2936 DEPTH is a count of how many nested mirrors can affect this mirror"
2943 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2947 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2948 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2950 If there is no transform for ht field, return nil.
2952 If there is a transform but it returns nil, return the empty
2953 string iff EMPTY-ON-NIL-P is true."
2954 (let* ((yas-text (yas--field-text-for-display field))
2955 (yas-modified-p (yas--field-modified-p field))
2956 (yas-moving-away-p nil)
2957 (transform (if (yas--mirror-p field-or-mirror)
2958 (yas--mirror-transform field-or-mirror)
2959 (yas--field-transform field-or-mirror)))
2960 (start-point (if (yas--mirror-p field-or-mirror)
2961 (yas--mirror-start field-or-mirror)
2962 (yas--field-start field-or-mirror)))
2963 (transformed (and transform
2965 (goto-char start-point)
2966 (let ((ret (yas--eval-lisp transform)))
2967 (or ret (and empty-on-nil-p "")))))))
2970 (defsubst yas--replace-all (from to &optional text)
2971 "Replace all occurrences from FROM to TO.
2973 With optional string TEXT do it in that string."
2975 (replace-regexp-in-string (regexp-quote from) to text t t)
2976 (goto-char (point-min))
2977 (while (search-forward from nil t)
2978 (replace-match to t t text))))
2980 (defun yas--snippet-find-field (snippet number)
2981 (find-if #'(lambda (field)
2982 (eq number (yas--field-number field)))
2983 (yas--snippet-fields snippet)))
2985 (defun yas--snippet-sort-fields (snippet)
2986 "Sort the fields of SNIPPET in navigation order."
2987 (setf (yas--snippet-fields snippet)
2988 (sort (yas--snippet-fields snippet)
2989 #'yas--snippet-field-compare)))
2991 (defun yas--snippet-field-compare (field1 field2)
2992 "Compare FIELD1 and FIELD2.
2994 The field with a number is sorted first. If they both have a
2995 number, compare through the number. If neither have, compare
2996 through the field's start point"
2997 (let ((n1 (yas--field-number field1))
2998 (n2 (yas--field-number field2)))
3001 (or (zerop n2) (and (not (zerop n1))
3006 (< (yas--field-start field1)
3007 (yas--field-start field2))))))
3009 (defun yas--field-probably-deleted-p (snippet field)
3010 "Guess if SNIPPET's FIELD should be skipped."
3012 ;; field must be zero length
3014 (zerop (- (yas--field-start field) (yas--field-end field)))
3017 ;; 1) is a nested field and it's been modified
3019 (and (yas--field-parent-field field)
3020 (yas--field-modified-p field))
3021 ;; 2) ends just before the snippet end
3023 (and (eq field (car (last (yas--snippet-fields snippet))))
3024 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3025 ;; the field numbered 0, just before the exit marker, should
3028 (not (zerop (yas--field-number field)))))
3030 (defun yas--snippets-at-point (&optional all-snippets)
3031 "Return a sorted list of snippets at point.
3033 The most recently-inserted snippets are returned first."
3035 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3036 (overlay-get ov 'yas--snippet))
3038 (overlays-in (point-min) (point-max))
3039 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3041 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3043 (defun yas-next-field-or-maybe-expand ()
3044 "Try to expand a snippet at a key before point.
3046 Otherwise delegate to `yas-next-field'."
3048 (if yas-triggers-in-field
3049 (let ((yas-fallback-behavior 'return-nil)
3050 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3052 (unless (yas-expand-from-trigger-key active-field)
3056 (defun yas-next-field (&optional arg)
3057 "Navigate to the ARGth next field.
3059 If there's none, exit the snippet."
3063 (snippet (first (yas--snippets-at-point)))
3064 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3065 (live-fields (remove-if #'(lambda (field)
3066 (and (not (eq field active-field))
3067 (yas--field-probably-deleted-p snippet field)))
3068 (yas--snippet-fields snippet)))
3069 (active-field-pos (position active-field live-fields))
3070 (target-pos (and active-field-pos (+ arg active-field-pos)))
3071 (target-field (and target-pos (nth target-pos live-fields))))
3072 ;; First check if we're moving out of a field with a transform
3074 (when (and active-field
3075 (yas--field-transform active-field))
3076 (let* ((yas-moving-away-p t)
3077 (yas-text (yas--field-text-for-display active-field))
3078 (yas-modified-p (yas--field-modified-p active-field)))
3079 ;; primary field transform: exit call to field-transform
3080 (yas--eval-lisp (yas--field-transform active-field))))
3081 ;; Now actually move...
3082 (cond ((and target-pos (>= target-pos (length live-fields)))
3083 (yas-exit-snippet snippet))
3085 (yas--move-to-field snippet target-field))
3089 (defun yas--place-overlays (snippet field)
3090 "Correctly place overlays for SNIPPET's FIELD."
3091 (yas--make-move-field-protection-overlays snippet field)
3092 (yas--make-move-active-field-overlay snippet field))
3094 (defun yas--move-to-field (snippet field)
3095 "Update SNIPPET to move to field FIELD.
3097 Also create some protection overlays"
3098 (goto-char (yas--field-start field))
3099 (yas--place-overlays snippet field)
3100 (overlay-put yas--active-field-overlay 'yas--field field)
3101 (let ((number (yas--field-number field)))
3102 ;; check for the special ${0: ...} field
3103 (if (and number (zerop number))
3105 (set-mark (yas--field-end field))
3106 (setf (yas--snippet-force-exit snippet)
3107 (or (yas--field-transform field)
3109 ;; make this field active
3110 (setf (yas--snippet-active-field snippet) field)
3111 ;; primary field transform: first call to snippet transform
3112 (unless (yas--field-modified-p field)
3113 (if (yas--field-update-display field)
3114 (yas--update-mirrors snippet)
3115 (setf (yas--field-modified-p field) nil))))))
3117 (defun yas-prev-field ()
3118 "Navigate to prev field. If there's none, exit the snippet."
3120 (yas-next-field -1))
3122 (defun yas-abort-snippet (&optional snippet)
3124 (let ((snippet (or snippet
3125 (car (yas--snippets-at-point)))))
3127 (setf (yas--snippet-force-exit snippet) t))))
3129 (defun yas-exit-snippet (snippet)
3130 "Goto exit-marker of SNIPPET."
3131 (interactive (list (first (yas--snippets-at-point))))
3133 (setf (yas--snippet-force-exit snippet) t)
3134 (goto-char (if (yas--snippet-exit snippet)
3135 (yas--exit-marker (yas--snippet-exit snippet))
3136 (overlay-end (yas--snippet-control-overlay snippet))))))
3138 (defun yas-exit-all-snippets ()
3139 "Exit all snippets."
3141 (mapc #'(lambda (snippet)
3142 (yas-exit-snippet snippet)
3143 (yas--check-commit-snippet))
3144 (yas--snippets-at-point 'all-snippets)))
3147 ;;; Some low level snippet-routines:
3149 (defvar yas--inhibit-overlay-hooks nil
3150 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3152 (defmacro yas--inhibit-overlay-hooks (&rest body)
3153 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3154 (declare (indent 0))
3155 `(let ((yas--inhibit-overlay-hooks t))
3158 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3159 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3161 (defun yas--commit-snippet (snippet)
3162 "Commit SNIPPET, but leave point as it is.
3164 This renders the snippet as ordinary text."
3166 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3168 ;; Save the end of the moribund snippet in case we need to revive it
3169 ;; its original expansion.
3171 (when (and control-overlay
3172 (overlay-buffer control-overlay))
3173 (setq yas-snippet-beg (overlay-start control-overlay))
3174 (setq yas-snippet-end (overlay-end control-overlay))
3175 (delete-overlay control-overlay))
3177 (yas--inhibit-overlay-hooks
3178 (when yas--active-field-overlay
3179 (delete-overlay yas--active-field-overlay))
3180 (when yas--field-protection-overlays
3181 (mapc #'delete-overlay yas--field-protection-overlays)))
3183 ;; stacked expansion: if the original expansion took place from a
3184 ;; field, make sure we advance it here at least to
3185 ;; `yas-snippet-end'...
3187 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3188 (when (and yas-snippet-end previous-field)
3189 (yas--advance-end-maybe previous-field yas-snippet-end)))
3191 ;; Convert all markers to points,
3193 (yas--markers-to-points snippet)
3195 ;; Take care of snippet revival
3197 (if yas-snippet-revival
3198 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3200 ;; Dismember the snippet... this is useful if we get called
3201 ;; again from `yas--take-care-of-redo'....
3202 (setf (yas--snippet-fields snippet) nil)))
3204 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3206 (defun yas--safely-run-hooks (hook-var)
3207 (condition-case error
3208 (run-hooks hook-var)
3210 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3213 (defun yas--check-commit-snippet ()
3214 "Check if point exited the currently active field of the snippet.
3216 If so cleans up the whole snippet up."
3217 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3218 (snippets-left snippets)
3219 (snippet-exit-transform))
3220 (dolist (snippet snippets)
3221 (let ((active-field (yas--snippet-active-field snippet)))
3222 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3223 (cond ((or snippet-exit-transform
3224 (not (and active-field (yas--field-contains-point-p active-field))))
3225 (setq snippets-left (delete snippet snippets-left))
3226 (setf (yas--snippet-force-exit snippet) nil)
3227 (yas--commit-snippet snippet))
3229 (or (not yas--active-field-overlay)
3230 (not (overlay-buffer yas--active-field-overlay))))
3232 ;; stacked expansion: this case is mainly for recent
3233 ;; snippet exits that place us back int the field of
3237 (yas--move-to-field snippet active-field)
3238 (yas--update-mirrors snippet)))
3241 (unless (or (null snippets) snippets-left)
3242 (if snippet-exit-transform
3243 (yas--eval-lisp-no-saves snippet-exit-transform))
3244 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3246 ;; Apropos markers-to-points:
3248 ;; This was found useful for performance reasons, so that an
3249 ;; excessive number of live markers aren't kept around in the
3250 ;; `buffer-undo-list'. However, in `markers-to-points', the
3251 ;; set-to-nil markers can't simply be discarded and replaced with
3252 ;; fresh ones in `points-to-markers'. The original marker that was
3253 ;; just set to nil has to be reused.
3255 ;; This shouldn't bring horrible problems with undo/redo, but it
3258 (defun yas--markers-to-points (snippet)
3259 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3260 where POINT is the original position of the marker and MARKER is
3261 the original marker object with the position set to nil."
3262 (dolist (field (yas--snippet-fields snippet))
3263 (let ((start (marker-position (yas--field-start field)))
3264 (end (marker-position (yas--field-end field))))
3265 (set-marker (yas--field-start field) nil)
3266 (set-marker (yas--field-end field) nil)
3267 (setf (yas--field-start field) (cons start (yas--field-start field)))
3268 (setf (yas--field-end field) (cons end (yas--field-end field))))
3269 (dolist (mirror (yas--field-mirrors field))
3270 (let ((start (marker-position (yas--mirror-start mirror)))
3271 (end (marker-position (yas--mirror-end mirror))))
3272 (set-marker (yas--mirror-start mirror) nil)
3273 (set-marker (yas--mirror-end mirror) nil)
3274 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3275 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3276 (let ((snippet-exit (yas--snippet-exit snippet)))
3278 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3279 (set-marker (yas--exit-marker snippet-exit) nil)
3280 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3282 (defun yas--points-to-markers (snippet)
3283 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3285 This is done by setting MARKER to POINT with `set-marker'."
3286 (dolist (field (yas--snippet-fields snippet))
3287 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3288 (car (yas--field-start field))))
3289 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3290 (car (yas--field-end field))))
3291 (dolist (mirror (yas--field-mirrors field))
3292 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3293 (car (yas--mirror-start mirror))))
3294 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3295 (car (yas--mirror-end mirror))))))
3296 (let ((snippet-exit (yas--snippet-exit snippet)))
3298 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3299 (car (yas--exit-marker snippet-exit)))))))
3301 (defun yas--field-contains-point-p (field &optional point)
3302 (let ((point (or point
3304 (and (>= point (yas--field-start field))
3305 (<= point (yas--field-end field)))))
3307 (defun yas--field-text-for-display (field)
3308 "Return the propertized display text for field FIELD."
3309 (buffer-substring (yas--field-start field) (yas--field-end field)))
3311 (defun yas--undo-in-progress ()
3312 "True if some kind of undo is in progress."
3313 (or undo-in-progress
3314 (eq this-command 'undo)
3315 (eq this-command 'redo)))
3317 (defun yas--make-control-overlay (snippet start end)
3318 "Create the control overlay that surrounds the snippet and
3320 (let ((overlay (make-overlay start
3325 (overlay-put overlay 'keymap yas-keymap)
3326 (overlay-put overlay 'priority 100)
3327 (overlay-put overlay 'yas--snippet snippet)
3330 (defun yas-skip-and-clear-or-delete-char (&optional field)
3331 "Clears unmodified field if at field start, skips to next tab.
3333 Otherwise deletes a character normally by calling `delete-char'."
3335 (let ((field (or field
3336 (and yas--active-field-overlay
3337 (overlay-buffer yas--active-field-overlay)
3338 (overlay-get yas--active-field-overlay 'yas--field)))))
3340 (not (yas--field-modified-p field))
3341 (eq (point) (marker-position (yas--field-start field))))
3342 (yas--skip-and-clear field)
3345 (call-interactively 'delete-char)))))
3347 (defun yas--skip-and-clear (field)
3348 "Deletes the region of FIELD and sets it's modified state to t."
3349 ;; Just before skipping-and-clearing the field, mark its children
3350 ;; fields as modified, too. If the children have mirrors-in-fields
3351 ;; this prevents them from updating erroneously (we're skipping and
3354 (yas--mark-this-and-children-modified field)
3355 (delete-region (yas--field-start field) (yas--field-end field)))
3357 (defun yas--mark-this-and-children-modified (field)
3358 (setf (yas--field-modified-p field) t)
3359 (let ((fom (yas--field-next field)))
3361 (yas--fom-parent-field fom))
3362 (when (and (eq (yas--fom-parent-field fom) field)
3364 (yas--mark-this-and-children-modified fom))
3365 (setq fom (yas--fom-next fom)))))
3367 (defun yas--make-move-active-field-overlay (snippet field)
3368 "Place the active field overlay in SNIPPET's FIELD.
3370 Move the overlay, or create it if it does not exit."
3371 (if (and yas--active-field-overlay
3372 (overlay-buffer yas--active-field-overlay))
3373 (move-overlay yas--active-field-overlay
3374 (yas--field-start field)
3375 (yas--field-end field))
3376 (setq yas--active-field-overlay
3377 (make-overlay (yas--field-start field)
3378 (yas--field-end field)
3380 (overlay-put yas--active-field-overlay 'priority 100)
3381 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3382 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3383 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3384 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3385 '(yas--on-field-overlay-modification))
3386 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3387 '(yas--on-field-overlay-modification))))
3389 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3390 "Clears the field and updates mirrors, conditionally.
3392 Only clears the field if it hasn't been modified and it point it
3393 at field start. This hook doesn't do anything if an undo is in
3395 (unless (or yas--inhibit-overlay-hooks
3396 (yas--undo-in-progress))
3397 (let* ((field (overlay-get overlay 'yas--field))
3398 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3400 (yas--advance-end-maybe field (overlay-end overlay))
3402 (yas--field-update-display field))
3403 (yas--update-mirrors snippet))
3405 (when (and (not after?)
3406 (not (yas--field-modified-p field))
3407 (eq (point) (if (markerp (yas--field-start field))
3408 (marker-position (yas--field-start field))
3409 (yas--field-start field))))
3410 (yas--skip-and-clear field))
3411 (setf (yas--field-modified-p field) t))))))
3413 ;;; Apropos protection overlays:
3415 ;; These exist for nasty users who will try to delete parts of the
3416 ;; snippet outside the active field. Actual protection happens in
3417 ;; `yas--on-protection-overlay-modification'.
3419 ;; Currently this signals an error which inhibits the command. For
3420 ;; commands that move point (like `kill-line'), point is restored in
3421 ;; the `yas--post-command-handler' using a global
3422 ;; `yas--protection-violation' variable.
3424 ;; Alternatively, I've experimented with an implementation that
3425 ;; commits the snippet before actually calling `this-command'
3426 ;; interactively, and then signals an error, which is ignored. but
3427 ;; blocks all other million modification hooks. This presented some
3428 ;; problems with stacked expansion.
3430 (defun yas--make-move-field-protection-overlays (snippet field)
3431 "Place protection overlays surrounding SNIPPET's FIELD.
3433 Move the overlays, or create them if they do not exit."
3434 (let ((start (yas--field-start field))
3435 (end (yas--field-end field)))
3436 ;; First check if the (1+ end) is contained in the buffer,
3437 ;; otherwise we'll have to do a bit of cheating and silently
3438 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3439 ;; when using stacked expansion
3441 (when (< (buffer-size) end)
3443 (yas--inhibit-overlay-hooks
3444 (goto-char (point-max))
3446 ;; go on to normal overlay creation/moving
3448 (cond ((and yas--field-protection-overlays
3449 (every #'overlay-buffer yas--field-protection-overlays))
3450 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3451 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3453 (setq yas--field-protection-overlays
3454 (list (make-overlay (1- start) start nil t nil)
3455 (make-overlay end (1+ end) nil t nil)))
3456 (dolist (ov yas--field-protection-overlays)
3457 (overlay-put ov 'face 'yas--field-debug-face)
3458 (overlay-put ov 'yas--snippet snippet)
3459 ;; (overlay-put ov 'evaporate t)
3460 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3462 (defvar yas--protection-violation nil
3463 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3465 Functions in the `post-command-hook', for example
3466 `yas--post-command-handler' can check it and reset its value to
3467 nil. The variables value is the point where the violation
3470 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3471 "Signals a snippet violation, then issues error.
3473 The error should be ignored in `debug-ignored-errors'"
3474 (unless yas--inhibit-overlay-hooks
3475 (cond ((not (or after?
3476 (yas--undo-in-progress)))
3477 (setq yas--protection-violation (point))
3478 (error "Exit the snippet first!")))))
3480 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3483 ;;; Snippet expansion and "stacked" expansion:
3485 ;; Stacked expansion is when you try to expand a snippet when already
3486 ;; inside a snippet expansion.
3488 ;; The parent snippet does not run its fields modification hooks
3489 ;; (`yas--on-field-overlay-modification' and
3490 ;; `yas--on-protection-overlay-modification') while the child snippet
3491 ;; is active. This means, among other things, that the mirrors of the
3492 ;; parent snippet are not updated, this only happening when one exits
3493 ;; the child snippet.
3495 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3496 ;; bits of code in `yas-expand-snippet' and
3497 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3500 ;; This was thought to be safer in an undo/redo perspective, but
3501 ;; maybe the correct implementation is to make the globals
3502 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3503 ;; snippet-local and be active even while the child snippet is
3504 ;; running. This would mean a lot of overlay modification hooks
3505 ;; running, but if managed correctly (including overlay priorities)
3506 ;; they should account for all situations...
3508 (defun yas-expand-snippet (content &optional start end expand-env)
3509 "Expand snippet CONTENT at current point.
3511 Text between START and END will be deleted before inserting
3512 template. EXPAND-ENV is are let-style variable to value bindings
3513 considered when expanding the snippet."
3514 (run-hooks 'yas-before-expand-snippet-hook)
3517 (let* ((yas-selected-text (or yas-selected-text
3518 (and (region-active-p)
3519 (buffer-substring-no-properties (region-beginning)
3522 (and (region-active-p)
3526 (and (region-active-p)
3529 (to-delete (and start
3531 (buffer-substring-no-properties start end)))
3534 (setq yas--indent-original-column (current-column))
3535 ;; Delete the region to delete, this *does* get undo-recorded.
3537 (when (and to-delete
3539 (delete-region start end))
3541 (cond ((listp content)
3542 ;; x) This is a snippet-command
3544 (yas--eval-lisp-no-saves content))
3546 ;; x) This is a snippet-snippet :-)
3548 ;; Narrow the region down to the content, shoosh the
3549 ;; `buffer-undo-list', and create the snippet, the new
3550 ;; snippet updates its mirrors once, so we are left with
3551 ;; some plain text. The undo action for deleting this
3552 ;; plain text will get recorded at the end.
3554 ;; stacked expansion: also shoosh the overlay modification hooks
3555 (let ((buffer-undo-list t))
3556 ;; snippet creation might evaluate users elisp, which
3557 ;; might generate errors, so we have to be ready to catch
3558 ;; them mostly to make the undo information
3560 (setq yas--start-column (current-column))
3561 (yas--inhibit-overlay-hooks
3564 (eval `(let* ,expand-env
3566 (yas--snippet-create start (point))))
3568 (yas--snippet-create start (point))))))
3570 ;; stacked-expansion: This checks for stacked expansion, save the
3571 ;; `yas--previous-active-field' and advance its boundary.
3573 (let ((existing-field (and yas--active-field-overlay
3574 (overlay-buffer yas--active-field-overlay)
3575 (overlay-get yas--active-field-overlay 'yas--field))))
3576 (when existing-field
3577 (setf (yas--snippet-previous-active-field snippet) existing-field)
3578 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3580 ;; Exit the snippet immediately if no fields
3582 (unless (yas--snippet-fields snippet)
3583 (yas-exit-snippet snippet))
3585 ;; Push two undo actions: the deletion of the inserted contents of
3586 ;; the new snippet (without the "key") followed by an apply of
3587 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3589 ;; A small exception, if `yas-also-auto-indent-first-line'
3590 ;; is t and `yas--indent' decides to indent the line to a
3591 ;; point before the actual expansion point, undo would be
3592 ;; messed up. We call the early point "newstart"". case,
3593 ;; and attempt to fix undo.
3595 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3596 (end (overlay-end (yas--snippet-control-overlay snippet))))
3597 (when (< newstart start)
3598 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3599 (push (cons newstart end) buffer-undo-list)
3600 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3602 ;; Now, schedule a move to the first field
3604 (let ((first-field (car (yas--snippet-fields snippet))))
3606 (sit-for 0) ;; fix issue 125
3607 (yas--move-to-field snippet first-field)))
3608 (yas--message 3 "snippet expanded.")
3611 (defun yas--take-care-of-redo (_beg _end snippet)
3612 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3614 Meant to exit in the `buffer-undo-list'."
3615 ;; slightly optimize: this action is only needed for snippets with
3616 ;; at least one field
3617 (when (yas--snippet-fields snippet)
3618 (yas--commit-snippet snippet)))
3620 (defun yas--snippet-revive (beg end snippet)
3621 "Revives SNIPPET and creates a control overlay from BEG to END.
3623 BEG and END are, we hope, the original snippets boundaries.
3624 All the markers/points exiting existing inside SNIPPET should point
3625 to their correct locations *at the time the snippet is revived*.
3627 After revival, push the `yas--take-care-of-redo' in the
3629 ;; Reconvert all the points to markers
3631 (yas--points-to-markers snippet)
3632 ;; When at least one editable field existed in the zombie snippet,
3633 ;; try to revive the whole thing...
3635 (let ((target-field (or (yas--snippet-active-field snippet)
3636 (car (yas--snippet-fields snippet)))))
3638 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3639 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3641 (yas--move-to-field snippet target-field)
3643 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3644 buffer-undo-list))))
3646 (defun yas--snippet-create (begin end)
3647 "Create a snippet from a template inserted at BEGIN to END.
3649 Returns the newly created snippet."
3651 (narrow-to-region begin end)
3652 (let ((snippet (yas--make-snippet)))
3654 (yas--snippet-parse-create snippet)
3656 ;; Sort and link each field
3657 (yas--snippet-sort-fields snippet)
3659 ;; Create keymap overlay for snippet
3660 (setf (yas--snippet-control-overlay snippet)
3661 (yas--make-control-overlay snippet (point-min) (point-max)))
3664 (goto-char (point-max))
3669 ;;; Apropos adjacencies and "fom's":
3671 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3672 ;; recently expanded snippet, we might actually have many fields,
3673 ;; mirrors (and the snippet exit) in the very same position in the
3674 ;; buffer. Therefore we need to single-link the
3675 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3676 ;; according to their original positions in the buffer.
3678 ;; Then we have operation `yas--advance-end-maybe' and
3679 ;; `yas--advance-start-maybe', which conditionally push the starts and
3680 ;; ends of these foms down the chain.
3682 ;; This allows for like the printf with the magic ",":
3684 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3685 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3687 (defun yas--fom-start (fom)
3688 (cond ((yas--field-p fom)
3689 (yas--field-start fom))
3690 ((yas--mirror-p fom)
3691 (yas--mirror-start fom))
3693 (yas--exit-marker fom))))
3695 (defun yas--fom-end (fom)
3696 (cond ((yas--field-p fom)
3697 (yas--field-end fom))
3698 ((yas--mirror-p fom)
3699 (yas--mirror-end fom))
3701 (yas--exit-marker fom))))
3703 (defun yas--fom-next (fom)
3704 (cond ((yas--field-p fom)
3705 (yas--field-next fom))
3706 ((yas--mirror-p fom)
3707 (yas--mirror-next fom))
3709 (yas--exit-next fom))))
3711 (defun yas--fom-parent-field (fom)
3712 (cond ((yas--field-p fom)
3713 (yas--field-parent-field fom))
3714 ((yas--mirror-p fom)
3715 (yas--mirror-parent-field fom))
3719 (defun yas--calculate-adjacencies (snippet)
3720 "Calculate adjacencies for fields or mirrors of SNIPPET.
3722 This is according to their relative positions in the buffer, and
3723 has to be called before the $-constructs are deleted."
3724 (let* ((fom-set-next-fom
3725 (lambda (fom nextfom)
3726 (cond ((yas--field-p fom)
3727 (setf (yas--field-next fom) nextfom))
3728 ((yas--mirror-p fom)
3729 (setf (yas--mirror-next fom) nextfom))
3731 (setf (yas--exit-next fom) nextfom)))))
3734 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3735 (yas--mirror-p fom2)
3736 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3737 (link-foms fom-set-next-fom))
3738 ;; make some yas--field, yas--mirror and yas--exit soup
3740 (when (yas--snippet-exit snippet)
3741 (push (yas--snippet-exit snippet) soup))
3742 (dolist (field (yas--snippet-fields snippet))
3744 (dolist (mirror (yas--field-mirrors field))
3745 (push mirror soup)))
3747 (sort soup compare-fom-begs))
3749 (reduce link-foms soup)))))
3751 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3752 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3754 Use the tightest containing field if more than one field contains
3755 the mirror. Intended to be called *before* the dollar-regions are
3757 (let ((min (point-min))
3759 (dolist (field (yas--snippet-fields snippet))
3760 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3761 (<= (yas--mirror-end mirror) (yas--field-end field))
3762 (< min (yas--field-start field))
3763 (< (yas--field-end field) max))
3764 (setq min (yas--field-start field)
3765 max (yas--field-end field))
3766 (setf (yas--mirror-parent-field mirror) field)))))
3768 (defun yas--advance-end-maybe (fom newend)
3769 "Maybe advance FOM's end to NEWEND if it needs it.
3773 * call `yas--advance-start-maybe' on FOM's next fom.
3775 * in case FOM is field call `yas--advance-end-maybe' on its parent
3778 Also, if FOM is an exit-marker, always call
3779 `yas--advance-start-maybe' on its next fom. This is because
3780 exit-marker have identical start and end markers."
3781 (cond ((and fom (< (yas--fom-end fom) newend))
3782 (set-marker (yas--fom-end fom) newend)
3783 (yas--advance-start-maybe (yas--fom-next fom) newend)
3784 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3786 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3788 (defun yas--advance-start-maybe (fom newstart)
3789 "Maybe advance FOM's start to NEWSTART if it needs it.
3791 If it does, also call `yas--advance-end-maybe' on FOM."
3792 (when (and fom (< (yas--fom-start fom) newstart))
3793 (set-marker (yas--fom-start fom) newstart)
3794 (yas--advance-end-maybe fom newstart)))
3796 (defun yas--advance-end-of-parents-maybe (field newend)
3797 "Like `yas--advance-end-maybe' but for parent fields.
3799 Only works for fields and doesn't care about the start of the
3800 next FOM. Works its way up recursively for parents of parents."
3802 (< (yas--field-end field) newend))
3803 (set-marker (yas--field-end field) newend)
3804 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3806 (defvar yas--dollar-regions nil
3807 "When expanding the snippet the \"parse-create\" functions add
3808 cons cells to this var.")
3810 (defvar yas--backquote-markers-and-strings nil
3811 "List of (MARKER . STRING) marking where the values from
3812 backquoted Lisp expressions should be inserted at the end of
3815 (defun yas--snippet-parse-create (snippet)
3816 "Parse a recently inserted snippet template, creating all
3817 necessary fields, mirrors and exit points.
3819 Meant to be called in a narrowed buffer, does various passes"
3820 (let ((parse-start (point)))
3821 ;; Reset the yas--dollar-regions
3823 (setq yas--dollar-regions nil)
3824 ;; protect just the backquotes
3826 (yas--protect-escapes nil '(?`))
3827 ;; replace all backquoted expressions
3829 (goto-char parse-start)
3830 (yas--save-backquotes)
3831 ;; protect escaped characters
3833 (yas--protect-escapes)
3834 ;; parse fields with {}
3836 (goto-char parse-start)
3837 (yas--field-parse-create snippet)
3838 ;; parse simple mirrors and fields
3840 (goto-char parse-start)
3841 (yas--simple-mirror-parse-create snippet)
3842 ;; parse mirror transforms
3844 (goto-char parse-start)
3845 (yas--transform-mirror-parse-create snippet)
3846 ;; calculate adjacencies of fields and mirrors
3848 (yas--calculate-adjacencies snippet)
3849 ;; Delete $-constructs
3851 (save-restriction (widen) (yas--delete-regions yas--dollar-regions))
3852 ;; restore backquoted expression values
3854 (yas--restore-backquotes)
3857 (goto-char parse-start)
3858 (yas--restore-escapes)
3859 ;; update mirrors for the first time
3861 (yas--update-mirrors snippet)
3862 ;; indent the best we can
3864 (goto-char parse-start)
3865 (yas--indent snippet)))
3867 (defun yas--indent-according-to-mode (snippet-markers)
3868 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3869 ;;; Apropos indenting problems....
3871 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3872 ;; is available. Some implementations of these functions delete text
3873 ;; before they insert. If there happens to be a marker just after
3874 ;; the text being deleted, the insertion actually happens after the
3875 ;; marker, which misplaces it.
3877 ;; This would also happen if we had used overlays with the
3878 ;; `front-advance' property set to nil.
3880 ;; This is why I have these `trouble-markers', they are the ones at
3881 ;; they are the ones at the first non-whitespace char at the line
3882 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3883 ;; we should be at the correct to restore them to. All other
3884 ;; non-trouble-markers have been *pushed* and don't need special
3887 (goto-char (yas--real-line-beginning))
3888 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3894 (indent-according-to-mode)
3895 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3897 (mapc #'(lambda (marker)
3898 (set-marker marker (point)))
3901 (defvar yas--indent-original-column nil)
3902 (defun yas--indent (snippet)
3903 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3904 ;; Look for those $>
3906 (while (re-search-forward "$>" nil t)
3907 (delete-region (match-beginning 0) (match-end 0))
3908 (when (not (eq yas-indent-line 'auto))
3909 (yas--indent-according-to-mode snippet-markers))))
3910 ;; Now do stuff for 'fixed and 'auto
3912 (cond ((eq yas-indent-line 'fixed)
3913 (while (and (zerop (forward-line))
3914 (zerop (current-column)))
3915 (indent-to-column yas--indent-original-column)))
3916 ((eq yas-indent-line 'auto)
3917 (let ((end (set-marker (make-marker) (point-max)))
3918 (indent-first-line-p yas-also-auto-indent-first-line))
3919 (while (and (zerop (if indent-first-line-p
3922 (setq indent-first-line-p nil))
3926 (yas--indent-according-to-mode snippet-markers))))
3930 (defun yas--collect-snippet-markers (snippet)
3931 "Make a list of all the markers used by SNIPPET."
3933 (dolist (field (yas--snippet-fields snippet))
3934 (push (yas--field-start field) markers)
3935 (push (yas--field-end field) markers)
3936 (dolist (mirror (yas--field-mirrors field))
3937 (push (yas--mirror-start mirror) markers)
3938 (push (yas--mirror-end mirror) markers)))
3939 (let ((snippet-exit (yas--snippet-exit snippet)))
3940 (when (and snippet-exit
3941 (marker-buffer (yas--exit-marker snippet-exit)))
3942 (push (yas--exit-marker snippet-exit) markers)))
3945 (defun yas--real-line-beginning ()
3946 (let ((c (char-after (line-beginning-position)))
3947 (n (line-beginning-position)))
3948 (while (or (eql c ?\ )
3951 (setq c (char-after n)))
3954 (defun yas--escape-string (escaped)
3955 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3957 (defun yas--protect-escapes (&optional text escaped)
3958 "Protect all escaped characters with their numeric ASCII value.
3960 With optional string TEXT do it in string instead of buffer."
3961 (let ((changed-text text)
3962 (text-provided-p text))
3963 (mapc #'(lambda (escaped)
3965 (yas--replace-all (concat "\\" (char-to-string escaped))
3966 (yas--escape-string escaped)
3967 (when text-provided-p changed-text))))
3968 (or escaped yas--escaped-characters))
3971 (defun yas--restore-escapes (&optional text escaped)
3972 "Restore all escaped characters from their numeric ASCII value.
3974 With optional string TEXT do it in string instead of the buffer."
3975 (let ((changed-text text)
3976 (text-provided-p text))
3977 (mapc #'(lambda (escaped)
3979 (yas--replace-all (yas--escape-string escaped)
3980 (char-to-string escaped)
3981 (when text-provided-p changed-text))))
3982 (or escaped yas--escaped-characters))
3985 (defun yas--save-backquotes ()
3986 "Save all the \"`(lisp-expression)`\"-style expressions
3987 with their evaluated value into `yas--backquote-markers-and-strings'."
3988 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3989 (let ((current-string (match-string-no-properties 1)) transformed)
3990 (delete-region (match-beginning 0) (match-end 0))
3991 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3992 (goto-char (match-beginning 0))
3994 (let ((marker (make-marker)))
3995 (insert "Y") ;; quite horrendous, I love it :)
3996 (set-marker marker (point))
3998 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4000 (defun yas--restore-backquotes ()
4001 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4002 (while yas--backquote-markers-and-strings
4003 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4004 (marker (car marker-and-string))
4005 (string (cdr marker-and-string)))
4011 (set-marker marker nil)))))
4013 (defun yas--scan-sexps (from count)
4015 (with-syntax-table (standard-syntax-table)
4016 (scan-sexps from count))
4020 (defun yas--make-marker (pos)
4021 "Create a marker at POS with nil `marker-insertion-type'."
4022 (let ((marker (set-marker (make-marker) pos)))
4023 (set-marker-insertion-type marker nil)
4026 (defun yas--field-parse-create (snippet &optional parent-field)
4027 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4029 The following count as a field:
4031 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4033 * \"${n: text$(expression)}, the same with a Lisp expression;
4034 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4036 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4038 When multiple expressions are found, only the last one counts."
4041 (while (re-search-forward yas--field-regexp nil t)
4042 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4043 (number (and (match-string-no-properties 1)
4044 (string-to-number (match-string-no-properties 1))))
4045 (brand-new-field (and real-match-end-0
4046 ;; break if on "$(" immediately
4047 ;; after the ":", this will be
4048 ;; caught as a mirror with
4050 (not (save-match-data
4051 (eq (string-match "$[ \t\n]*("
4052 (match-string-no-properties 2)) 0)))
4053 ;; allow ${0: some exit text}
4054 ;; (not (and number (zerop number)))
4055 (yas--make-field number
4056 (yas--make-marker (match-beginning 2))
4057 (yas--make-marker (1- real-match-end-0))
4059 (when brand-new-field
4060 (goto-char real-match-end-0)
4061 (push (cons (1- real-match-end-0) real-match-end-0)
4062 yas--dollar-regions)
4063 (push (cons (match-beginning 0) (match-beginning 2))
4064 yas--dollar-regions)
4065 (push brand-new-field (yas--snippet-fields snippet))
4068 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4069 (goto-char (point-min))
4070 (yas--field-parse-create snippet brand-new-field)))))))
4071 ;; if we entered from a parent field, now search for the
4072 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4073 ;; primary field transformations
4077 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4078 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4079 ;; commit the primary field transformation if:
4081 ;; 1. we don't find it in yas--dollar-regions (a subnested
4082 ;; field) might have already caught it.
4084 ;; 2. we really make sure we have either two '$' or some
4085 ;; text and a '$' after the colon ':'. This is a FIXME: work
4086 ;; my regular expressions and end these ugly hacks.
4088 (when (and real-match-end-1
4089 (not (member (cons (match-beginning 0)
4091 yas--dollar-regions))
4093 (char-before (1- (match-beginning 1))))))
4094 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4096 (setf (yas--field-transform parent-field)
4097 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4098 (push (cons (match-beginning 0) real-match-end-1)
4099 yas--dollar-regions)))))))
4101 (defun yas--transform-mirror-parse-create (snippet)
4102 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4103 (while (re-search-forward yas--transform-mirror-regexp nil t)
4104 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4105 (number (string-to-number (match-string-no-properties 1)))
4107 (not (zerop number))
4108 (yas--snippet-find-field snippet number)))
4110 (and real-match-end-0
4112 (yas--make-mirror (yas--make-marker (match-beginning 0))
4113 (yas--make-marker (match-beginning 0))
4115 (yas--restore-escapes
4116 (buffer-substring-no-properties (match-beginning 2)
4117 (1- real-match-end-0))))))))
4118 (when brand-new-mirror
4119 (push brand-new-mirror
4120 (yas--field-mirrors field))
4121 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4122 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4124 (defun yas--simple-mirror-parse-create (snippet)
4125 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4126 (while (re-search-forward yas--simple-mirror-regexp nil t)
4127 (let ((number (string-to-number (match-string-no-properties 1))))
4128 (cond ((zerop number)
4130 (setf (yas--snippet-exit snippet)
4131 (yas--make-exit (yas--make-marker (match-end 0))))
4133 (goto-char (match-beginning 0))
4134 (when yas-wrap-around-region
4135 (cond (yas-selected-text
4136 (insert yas-selected-text))
4137 ((and (eq yas-wrap-around-region 'cua)
4140 (insert (prog1 (get-register ?0)
4141 (set-register ?0 nil))))))
4142 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4143 yas--dollar-regions)))
4145 (let ((field (yas--snippet-find-field snippet number)))
4147 (let ((brand-new-mirror (yas--make-mirror
4148 (yas--make-marker (match-beginning 0))
4149 (yas--make-marker (match-beginning 0))
4151 (push brand-new-mirror
4152 (yas--field-mirrors field))
4153 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4154 (push (yas--make-field number
4155 (yas--make-marker (match-beginning 0))
4156 (yas--make-marker (match-beginning 0))
4158 (yas--snippet-fields snippet))))
4159 (push (cons (match-beginning 0) (match-end 0))
4160 yas--dollar-regions))))))
4162 (defun yas--delete-regions (regions)
4163 "Sort disjuct REGIONS by start point, then delete from the back."
4164 (mapc #'(lambda (reg)
4165 (delete-region (car reg) (cdr reg)))
4168 (>= (car r1) (car r2))))))
4170 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4171 (let* ((parent (yas--mirror-parent-field mirror))
4172 (parents-mirrors (and parent
4173 (yas--field-mirrors parent))))
4174 (or (yas--mirror-depth mirror)
4175 (setf (yas--mirror-depth mirror)
4176 (cond ((memq mirror traversed)
4178 ((and parent parents-mirrors)
4180 (mapcar #'(lambda (m)
4181 (yas--calculate-mirror-depth m
4190 (defun yas--update-mirrors (snippet)
4191 "Update all the mirrors of SNIPPET."
4193 (dolist (field-and-mirror (sort
4194 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4195 ;; where F is the field that M is mirroring
4197 (mapcan #'(lambda (field)
4198 (mapcar #'(lambda (mirror)
4199 (cons field mirror))
4200 (yas--field-mirrors field)))
4201 (yas--snippet-fields snippet))
4202 ;; then sort this list so that entries with mirrors with parent
4203 ;; fields appear before. This was important for fixing #290, and
4204 ;; luckily also handles the case where a mirror in a field causes
4205 ;; another mirror to need reupdating
4207 #'(lambda (field-and-mirror1 field-and-mirror2)
4208 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4209 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4210 (let* ((field (car field-and-mirror))
4211 (mirror (cdr field-and-mirror))
4212 (parent-field (yas--mirror-parent-field mirror)))
4213 ;; before updating a mirror with a parent-field, maybe advance
4217 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4218 ;; update this mirror
4220 (yas--mirror-update-display mirror field)
4221 ;; `yas--place-overlays' is needed if the active field and
4222 ;; protected overlays have been changed because of insertions
4223 ;; in `yas--mirror-update-display'
4225 (when (eq field (yas--snippet-active-field snippet))
4226 (yas--place-overlays snippet field))))))
4228 (defun yas--mirror-update-display (mirror field)
4229 "Update MIRROR according to FIELD (and mirror transform)."
4231 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4232 (reflection (and (not (and mirror-parent-field
4233 (yas--field-modified-p mirror-parent-field)))
4234 (or (yas--apply-transform mirror field 'empty-on-nil)
4235 (yas--field-text-for-display field)))))
4236 (when (and reflection
4237 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4238 (yas--mirror-end mirror)))))
4239 (goto-char (yas--mirror-start mirror))
4240 (yas--inhibit-overlay-hooks
4241 (insert reflection))
4242 (if (> (yas--mirror-end mirror) (point))
4243 (delete-region (point) (yas--mirror-end mirror))
4244 (set-marker (yas--mirror-end mirror) (point))
4245 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4246 ;; super-special advance
4247 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4249 (defun yas--field-update-display (field)
4250 "Much like `yas--mirror-update-display', but for fields."
4251 (when (yas--field-transform field)
4252 (let ((transformed (and (not (eq (yas--field-number field) 0))
4253 (yas--apply-transform field field))))
4254 (when (and transformed
4255 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4256 (yas--field-end field)))))
4257 (setf (yas--field-modified-p field) t)
4258 (goto-char (yas--field-start field))
4259 (yas--inhibit-overlay-hooks
4260 (insert transformed)
4261 (if (> (yas--field-end field) (point))
4262 (delete-region (point) (yas--field-end field))
4263 (set-marker (yas--field-end field) (point))
4264 (yas--advance-start-maybe (yas--field-next field) (point)))
4268 ;;; Post-command hook:
4270 (defun yas--post-command-handler ()
4271 "Handles various yasnippet conditions after each command."
4272 (cond (yas--protection-violation
4273 (goto-char yas--protection-violation)
4274 (setq yas--protection-violation nil))
4275 ((eq 'undo this-command)
4277 ;; After undo revival the correct field is sometimes not
4278 ;; restored correctly, this condition handles that
4280 (let* ((snippet (car (yas--snippets-at-point)))
4281 (target-field (and snippet
4282 (find-if-not #'(lambda (field)
4283 (yas--field-probably-deleted-p snippet field))
4285 (cons (yas--snippet-active-field snippet)
4286 (yas--snippet-fields snippet)))))))
4288 (yas--move-to-field snippet target-field))))
4289 ((not (yas--undo-in-progress))
4290 ;; When not in an undo, check if we must commit the snippet
4291 ;; (user exited it).
4292 (yas--check-commit-snippet))))
4296 ;; The docstrings for some functions are generated dynamically
4297 ;; depending on the context.
4299 (put 'yas-expand 'function-documentation
4300 '(yas--expand-from-trigger-key-doc t))
4301 (defun yas--expand-from-trigger-key-doc (context)
4302 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4303 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4304 (fallback-description
4305 (cond ((eq yas-fallback-behavior 'call-other-command)
4306 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4308 (format "call command `%s'."
4309 (pp-to-string fallback)))
4310 "do nothing (`yas-expand' doesn't shadow\nanything).")))
4311 ((eq yas-fallback-behavior 'return-nil)
4313 (t "defer to `yas-fallback-behavior' (which see)."))))
4314 (concat "Expand a snippet before point. If no snippet
4315 expansion is possible, "
4316 fallback-description
4317 "\n\nOptional argument FIELD is for non-interactive use and is an
4318 object satisfying `yas--field-p' to restrict the expansion to.")))
4320 (put 'yas-expand-from-keymap 'function-documentation
4321 '(yas--expand-from-keymap-doc t))
4322 (defun yas--expand-from-keymap-doc (context)
4323 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4324 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4325 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4326 (when (and context (eq this-command 'describe-key))
4327 (let* ((vec (this-single-command-keys))
4328 (templates (mapcan #'(lambda (table)
4329 (yas--fetch table vec))
4330 (yas--get-snippet-tables)))
4331 (yas--direct-keymaps nil)
4332 (fallback (key-binding vec)))
4333 (concat "In this case, "
4335 (concat "these snippets are bound to this key:\n"
4336 (yas--template-pretty-list templates)
4337 "\n\nIf none of these expands, "))
4339 (format "fallback `%s' will be called." (pp-to-string fallback)))
4340 "no fallback keybinding is called."))))))
4342 (defun yas--template-pretty-list (templates)
4344 (yas-buffer-local-condition 'always))
4345 (dolist (plate templates)
4346 (setq acc (concat acc "\n*) "
4347 (propertize (concat "\\\\snippet `" (car plate) "'")
4348 'yasnippet (cdr plate)))))
4351 (define-button-type 'help-snippet-def
4352 :supertype 'help-xref
4353 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4354 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4356 (defun yas--snippet-description-finish-runonce ()
4357 "Final adjustments for the help buffer when snippets are concerned."
4358 (yas--create-snippet-xrefs)
4359 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4361 (defun yas--create-snippet-xrefs ()
4363 (goto-char (point-min))
4364 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4365 (let ((template (get-text-property (match-beginning 1)
4368 (help-xref-button 1 'help-snippet-def template)
4369 (kill-region (match-end 1) (match-end 0))
4370 (kill-region (match-beginning 0) (match-beginning 1)))))))
4374 (defvar yas-verbosity 4
4375 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4377 (defun yas--message (level message &rest args)
4378 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4379 (when (> yas-verbosity level)
4380 (message "%s" (apply #'yas--format message args))))
4382 (defun yas--format (format-control &rest format-args)
4383 (apply #'format (concat "[yas] " format-control) format-args))
4390 ;; `locate-dominating-file'
4391 ;; `region-active-p'
4393 ;; added for compatibility in emacsen < 23
4394 (unless (>= emacs-major-version 23)
4395 (unless (fboundp 'region-active-p)
4396 (defun region-active-p () (and transient-mark-mode mark-active)))
4398 (unless (fboundp 'locate-dominating-file)
4399 (defvar locate-dominating-stop-dir-regexp
4400 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4401 "Regexp of directory names which stop the search in `locate-dominating-file'.
4402 Any directory whose name matches this regexp will be treated like
4403 a kind of root directory by `locate-dominating-file' which will stop its search
4404 when it bumps into it.
4405 The default regexp prevents fruitless and time-consuming attempts to find
4406 special files in directories in which filenames are interpreted as hostnames,
4407 or mount points potentially requiring authentication as a different user.")
4409 (defun locate-dominating-file (file name)
4410 "Look up the directory hierarchy from FILE for a file named NAME.
4411 Stop at the first parent directory containing a file NAME,
4412 and return the directory. Return nil if not found."
4413 ;; We used to use the above locate-dominating-files code, but the
4414 ;; directory-files call is very costly, so we're much better off doing
4415 ;; multiple calls using the code in here.
4417 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4418 ;; `name' in /home or in /.
4419 (setq file (abbreviate-file-name file))
4422 (while (not (or root
4424 ;; FIXME: Disabled this heuristic because it is sometimes
4426 ;; As a heuristic, we stop looking up the hierarchy of
4427 ;; directories as soon as we find a directory belonging
4428 ;; to another user. This should save us from looking in
4429 ;; things like /net and /afs. This assumes that all the
4430 ;; files inside a project belong to the same user.
4431 ;; (let ((prev-user user))
4432 ;; (setq user (nth 2 (file-attributes file)))
4433 ;; (and prev-user (not (equal user prev-user))))
4434 (string-match locate-dominating-stop-dir-regexp file)))
4435 (setq try (file-exists-p (expand-file-name name file)))
4436 (cond (try (setq root file))
4437 ((equal file (setq file (file-name-directory
4438 (directory-file-name file))))
4443 ;;; Backward compatibility to yasnippet <= 0.7
4445 (defvar yas--backported-syms '(;; `defcustom's
4448 yas-prompt-functions
4450 yas-also-auto-indent-first-line
4452 yas-triggers-in-field
4453 yas-fallback-behavior
4454 yas-choose-keys-first
4455 yas-choose-tables-first
4458 yas-wrap-around-region
4461 yas-expand-only-for-last-commands
4462 yas-field-highlight-face
4464 ;; these vars can be customized as well
4470 yas-after-exit-snippet-hook
4471 yas-before-expand-snippet-hook
4472 yas-buffer-local-condition
4475 ;; prompting functions
4480 yas-completing-prompt
4483 ;; interactive functions
4488 yas-direct-keymaps-reload
4492 yas-compile-directory
4495 yas-expand-from-trigger-key
4496 yas-expand-from-keymap
4498 yas-visit-snippet-file
4500 yas-load-snippet-buffer
4503 yas-next-field-or-maybe-expand
4508 yas-exit-all-snippets
4509 yas-skip-and-clear-or-delete-char
4511 ;; symbols that I "exported" for use
4512 ;; in snippets and hookage
4530 yas-default-from-field
4533 yas-define-condition-cache
4534 yas-hippie-try-expand
4536 ;; debug definitions
4537 ;; yas-debug-snippet-vars
4538 ;; yas-exterminate-package
4541 ;; testing definitions
4542 ;; yas-should-expand
4543 ;; yas-should-not-expand
4545 ;; yas-make-file-or-dirs
4547 ;; yas-saving-variables
4548 ;; yas-call-with-snippet-dirs
4549 ;; yas-with-snippet-dirs
4551 "Backported yasnippet symbols.
4553 They are mapped to \"yas/*\" variants.")
4555 (dolist (sym yas--backported-syms)
4556 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4558 (make-obsolete-variable backported sym "yasnippet 0.8")
4559 (defvaralias backported sym))
4561 (make-obsolete backported sym "yasnippet 0.8")
4562 (defalias backported sym))))
4564 (defvar yas--exported-syms
4566 (mapatoms (lambda (atom)
4567 (if (and (or (and (boundp atom)
4568 (not (get atom 'byte-obsolete-variable)))
4570 (not (get atom 'byte-obsolete-info))))
4571 (string-match-p "^yas-[^-]" (symbol-name atom)))
4572 (push atom exported))))
4574 "Exported yasnippet symbols.
4576 i.e. the ones with \"yas-\" single dash prefix. I will try to
4577 keep them in future yasnippet versions and other elisp libraries
4578 can more or less safely rely upon them.")
4581 (provide 'yasnippet)
4583 ;;; yasnippet.el ends here
4586 ;; byte-compile-warnings: (not cl-functions)