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
137 (defvar yas--editing-template)
138 (defvar yas--guessed-modes)
139 (defvar yas--indent-original-column)
140 (defvar yas--scheduled-jit-loads)
142 (defvar yas-selected-text)
143 (defvar yas-verbosity)
144 (defvar yas--current-template)
147 ;;; User customizable variables
149 (defgroup yasnippet nil
150 "Yet Another Snippet extension"
153 (defvar yas--load-file-name load-file-name
154 "Store the filename that yasnippet.el was originally loaded from.")
156 (defcustom yas-snippet-dirs (remove nil
157 (list "~/.emacs.d/snippets"
158 (when yas--load-file-name
159 (concat (file-name-directory yas--load-file-name) "snippets"))))
160 "Directory or list of snippet dirs for each major mode.
162 The directory where user-created snippets are to be stored. Can
163 also be a list of directories. In that case, when used for
164 bulk (re)loading of snippets (at startup or via
165 `yas-reload-all'), directories appearing earlier in the list
166 shadow other dir's snippets. Also, the first directory is taken
167 as the default for storing the user's new snippets."
168 :type '(choice (string :tag "Single directory (string)")
169 (repeat :args (string) :tag "List of directories (strings)"))
172 :set #'(lambda (symbol new)
173 (let ((old (and (boundp symbol)
174 (symbol-value symbol))))
175 (set-default symbol new)
176 (unless (or (not (fboundp 'yas-reload-all))
180 (defun yas-snippet-dirs ()
181 "Return `yas-snippet-dirs' (which see) as a list."
182 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
184 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
186 (defcustom yas-new-snippet-default "\
187 # -*- mode: snippet; require-final-newline: nil -*-
189 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
190 # binding: ${4:direct-keybinding}}
193 "Default snippet to use when creating a new snippet.
194 If nil, don't use any snippet."
198 (defcustom yas-prompt-functions '(yas-x-prompt
200 yas-completing-prompt
203 "Functions to prompt for keys, templates, etc interactively.
205 These functions are called with the following arguments:
207 - PROMPT: A string to prompt the user
209 - CHOICES: a list of strings or objects.
211 - optional DISPLAY-FN : A function that, when applied to each of
212 the objects in CHOICES will return a string.
214 The return value of any function you put here should be one of
215 the objects in CHOICES, properly formatted with DISPLAY-FN (if
218 - To signal that your particular style of prompting is
219 unavailable at the moment, you can also have the function return
222 - To signal that the user quit the prompting process, you can
225 (signal 'quit \"user quit!\")."
226 :type '(repeat function)
229 (defcustom yas-indent-line 'auto
230 "Controls indenting applied to a recent snippet expansion.
232 The following values are possible:
234 - `fixed' Indent the snippet to the current column;
236 - `auto' Indent each line of the snippet with `indent-according-to-mode'
238 Every other value means don't apply any snippet-side indentation
239 after expansion (the manual per-line \"$>\" indentation still
241 :type '(choice (const :tag "Nothing" nothing)
242 (const :tag "Fixed" fixed)
243 (const :tag "Auto" auto))
246 (defcustom yas-also-auto-indent-first-line nil
247 "Non-nil means also auto indent first line according to mode.
249 Naturally this is only valid when `yas-indent-line' is `auto'"
253 (defcustom yas-snippet-revival t
254 "Non-nil means re-activate snippet fields after undo/redo."
258 (defcustom yas-triggers-in-field nil
259 "If non-nil, allow stacked expansions (snippets inside snippets).
261 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
266 (defcustom yas-fallback-behavior 'call-other-command
267 "How to act when `yas-expand' does *not* expand a snippet.
269 - `call-other-command' means try to temporarily disable YASnippet
270 and call the next command bound to whatever key was used to
273 - nil or the symbol `return-nil' mean do nothing. (and
274 `yas-expand' returns nil)
276 - A Lisp form (apply COMMAND . ARGS) means interactively call
277 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
278 with ARGS as arguments."
279 :type '(choice (const :tag "Call previous command" call-other-command)
280 (const :tag "Do nothing" return-nil))
283 (defcustom yas-choose-keys-first nil
284 "If non-nil, prompt for snippet key first, then for template.
286 Otherwise prompts for all possible snippet names.
288 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
292 (defcustom yas-choose-tables-first nil
293 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
295 Otherwise, user chooses between the merging together of all
298 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
302 (defcustom yas-use-menu 'abbreviate
303 "Display a YASnippet menu in the menu bar.
305 When non-nil, submenus for each snippet table will be listed
306 under the menu \"Yasnippet\".
308 - If set to `abbreviate', only the current major-mode
309 menu and the modes set in `yas--extra-modes' are listed.
311 - If set to `full', every submenu is listed
313 - If set to `nil', hide the menu.
315 Any other non-nil value, every submenu is listed."
316 :type '(choice (const :tag "Full" full)
317 (const :tag "Abbreviate" abbreviate)
318 (const :tag "No menu" nil))
321 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
323 (char-to-string ?\x21E5))) ;; little ->| sign
325 "The text that will be used in menu to represent the trigger."
329 (defcustom yas-wrap-around-region nil
330 "If non-nil, snippet expansion wraps around selected region.
332 The wrapping occurs just before the snippet's exit marker. This
333 can be overridden on a per-snippet basis."
337 (defcustom yas-good-grace t
338 "If non-nil, don't raise errors in inline elisp evaluation.
340 An error string \"[yas] error\" is returned instead."
344 (defcustom yas-visit-from-menu nil
345 "If non-nil visit snippets's files from menu, instead of expanding them.
347 This can only work when snippets are loaded from files."
351 (defcustom yas-expand-only-for-last-commands nil
352 "List of `last-command' values to restrict tab-triggering to, or nil.
354 Leave this set at nil (the default) to be able to trigger an
355 expansion simply by placing the cursor after a valid tab trigger,
356 using whichever commands.
358 Optionally, set this to something like '(self-insert-command) if
359 you to wish restrict expansion to only happen when the last
360 letter of the snippet tab trigger was typed immediately before
361 the trigger key itself."
362 :type '(repeat function)
365 ;; Only two faces, and one of them shouldn't even be used...
367 (defface yas-field-highlight-face
368 '((t (:inherit 'region)))
369 "The face used to highlight the currently active field of a snippet"
372 (defface yas--field-debug-face
374 "The face used for debugging some overlays normally hidden"
378 ;;; User-visible variables
380 (defvar yas-keymap (let ((map (make-sparse-keymap)))
381 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
382 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
383 (define-key map [(shift tab)] 'yas-prev-field)
384 (define-key map [backtab] 'yas-prev-field)
385 (define-key map (kbd "C-g") 'yas-abort-snippet)
386 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
388 "The active keymap while a snippet expansion is in progress.")
390 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()"
391 #'yas-try-key-from-whitespace)
392 "Syntaxes and functions to help look for trigger keys before point.
394 Each element in this list specifies how to skip buffer positions
395 backwards and look for the start of a trigger key.
397 Each element can be either a string or a function receiving the
398 original point as an argument. A string element is simply passed
399 to `skip-syntax-backward' whereas a function element is called
400 with no arguments and should also place point before the original
403 The string between the resulting buffer position and the original
404 point is matched against the trigger keys in the active snippet
407 If no expandable snippets are found, the next element is the list
408 is tried, unless a function element returned the symbol `again',
409 in which case it is called again from the previous position and
410 may once more reposition point.
412 For example, if `yas-key-syntaxes'' value is '(\"w\" \"w_\"),
413 trigger keys composed exclusively of \"word\"-syntax characters
414 are looked for first. Failing that, longer keys composed of
415 \"word\" or \"symbol\" syntax are looked for. Therefore,
420 will, according to the \"w\" element first try \"barbaz\". If
421 that isn't a trigger key, \"foo-barbaz\" is tried, respecting the
422 second \"w_\" element. Notice that even if \"baz\" is a trigger
423 key for an active snippet, it won't be expanded, unless a
424 function is added to `yas-key-syntaxes' that eventually places
425 point between \"bar\" and \"baz\".
427 See also Info node `(elisp) Syntax Descriptors'.")
429 (defvar yas-after-exit-snippet-hook
431 "Hooks to run after a snippet exited.
433 The hooks will be run in an environment where some variables bound to
436 `yas-snippet-beg' : The beginning of the region of the snippet.
438 `yas-snippet-end' : Similar to beg.
440 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
442 (defvar yas-before-expand-snippet-hook
444 "Hooks to run just before expanding a snippet.")
446 (defvar yas-buffer-local-condition
447 '(if (and (or (fourth (syntax-ppss))
448 (fifth (syntax-ppss)))
450 (eq this-command 'yas-expand-from-trigger-key))
451 '(require-snippet-condition . force-in-comment)
453 "Snippet expanding condition.
455 This variable is a Lisp form which is evaluated every time a
456 snippet expansion is attempted:
458 * If it evaluates to nil, no snippets can be expanded.
460 * If it evaluates to the a cons (require-snippet-condition
463 * Snippets bearing no \"# condition:\" directive are not
466 * Snippets bearing conditions that evaluate to nil (or
467 produce an error) won't be considered.
469 * If the snippet has a condition that evaluates to non-nil
472 * If REQUIREMENT is t, the snippet is considered
474 * If REQUIREMENT is `eq' RESULT, the snippet is
477 * Otherwise, the snippet is not considered.
479 * If it evaluates to the symbol 'always, all snippets are
480 considered for expansion, regardless of any conditions.
482 * If it evaluates to t or some other non-nil value
484 * Snippet bearing no conditions, or conditions that
485 evaluate to non-nil, are considered for expansion.
487 * Otherwise, the snippet is not considered.
489 Here's an example preventing snippets from being expanded from
490 inside comments, in `python-mode' only, with the exception of
491 snippets returning the symbol 'force-in-comment in their
494 (add-hook 'python-mode-hook
496 (setq yas-buffer-local-condition
497 '(if (python-in-string/comment)
498 '(require-snippet-condition . force-in-comment)
501 The default value is similar, it filters out potential snippet
502 expansions inside comments and string literals, unless the
503 snippet itself contains a condition that returns the symbol
504 `force-in-comment'.")
507 ;;; Internal variables
509 (defvar yas--version "0.8.0beta")
511 (defvar yas--menu-table (make-hash-table)
512 "A hash table of MAJOR-MODE symbols to menu keymaps.")
514 (defvar yas--known-modes
515 '(ruby-mode rst-mode markdown-mode)
516 "A list of mode which is well known but not part of Emacs.")
518 (defvar yas--escaped-characters
519 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
520 "List of characters which *might* need to be escaped.")
522 (defconst yas--field-regexp
523 "${\\([0-9]+:\\)?\\([^}]*\\)}"
524 "A regexp to *almost* recognize a field.")
526 (defconst yas--multi-dollar-lisp-expression-regexp
527 "$+[ \t\n]*\\(([^)]*)\\)"
528 "A regexp to *almost* recognize a \"$(...)\" expression.")
530 (defconst yas--backquote-lisp-expression-regexp
532 "A regexp to recognize a \"`lisp-expression`\" expression." )
534 (defconst yas--transform-mirror-regexp
535 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
536 "A regexp to *almost* recognize a mirror with a transform.")
538 (defconst yas--simple-mirror-regexp
540 "A regexp to recognize a simple mirror.")
542 (defvar yas--snippet-id-seed 0
543 "Contains the next id for a snippet.")
545 (defun yas--snippet-next-id ()
546 (let ((id yas--snippet-id-seed))
547 (incf yas--snippet-id-seed)
553 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
554 (defvar last-buffer-undo-list nil)
556 (defvar yas--minor-mode-menu nil
557 "Holds the YASnippet menu.")
559 (defvar yas-minor-mode-map
560 (let ((map (make-sparse-keymap)))
561 (define-key map [(tab)] 'yas-expand)
562 (define-key map (kbd "TAB") 'yas-expand)
563 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
564 (define-key map "\C-c&\C-n" 'yas-new-snippet)
565 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
567 "The keymap used when `yas-minor-mode' is active.")
569 (easy-menu-define yas--minor-mode-menu
571 "Menu used when `yas-minor-mode' is active."
572 '("YASnippet" :visible yas-use-menu
574 ["Expand trigger" yas-expand
575 :help "Possibly expand tab trigger before point"]
576 ["Insert at point..." yas-insert-snippet
577 :help "Prompt for an expandable snippet and expand it at point"]
578 ["New snippet..." yas-new-snippet
579 :help "Create a new snippet in an appropriate directory"]
580 ["Visit snippet file..." yas-visit-snippet-file
581 :help "Prompt for an expandable snippet and find its file"]
583 ("Snippet menu behaviour"
584 ["Visit snippets" (setq yas-visit-from-menu t)
585 :help "Visit snippets from the menu"
586 :active t :style radio :selected yas-visit-from-menu]
587 ["Expand snippets" (setq yas-visit-from-menu nil)
588 :help "Expand snippets from the menu"
589 :active t :style radio :selected (not yas-visit-from-menu)]
591 ["Show all known modes" (setq yas-use-menu 'full)
592 :help "Show one snippet submenu for each loaded table"
593 :active t :style radio :selected (eq yas-use-menu 'full)]
594 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
595 :help "Show only snippet submenus for the current active modes"
596 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
598 ["Auto" (setq yas-indent-line 'auto)
599 :help "Indent each line of the snippet with `indent-according-to-mode'"
600 :active t :style radio :selected (eq yas-indent-line 'auto)]
601 ["Fixed" (setq yas-indent-line 'fixed)
602 :help "Indent the snippet to the current column"
603 :active t :style radio :selected (eq yas-indent-line 'fixed)]
604 ["None" (setq yas-indent-line 'none)
605 :help "Don't apply any particular snippet indentation after expansion"
606 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
608 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
609 (not yas-also-auto-indent-first-line))
610 :help "When auto-indenting also, auto indent the first line menu"
611 :active (eq yas-indent-line 'auto)
612 :style toggle :selected yas-also-auto-indent-first-line]
615 ["System X-widget" (setq yas-prompt-functions
617 (remove 'yas-x-prompt
618 yas-prompt-functions)))
619 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
620 :active t :style radio :selected (eq (car yas-prompt-functions)
622 ["Dropdown-list" (setq yas-prompt-functions
623 (cons 'yas-dropdown-prompt
624 (remove 'yas-dropdown-prompt
625 yas-prompt-functions)))
626 :help "Use a special dropdown list"
627 :active t :style radio :selected (eq (car yas-prompt-functions)
628 'yas-dropdown-prompt)]
629 ["Ido" (setq yas-prompt-functions
630 (cons 'yas-ido-prompt
631 (remove 'yas-ido-prompt
632 yas-prompt-functions)))
633 :help "Use an ido-style minibuffer prompt"
634 :active t :style radio :selected (eq (car yas-prompt-functions)
636 ["Completing read" (setq yas-prompt-functions
637 (cons 'yas-completing-prompt
638 (remove 'yas-completing-prompt
639 yas-prompt-functions)))
640 :help "Use a normal minibuffer prompt"
641 :active t :style radio :selected (eq (car yas-prompt-functions)
642 'yas-completing-prompt)]
645 ["Wrap region in exit marker"
646 (setq yas-wrap-around-region
647 (not yas-wrap-around-region))
648 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
649 :style toggle :selected yas-wrap-around-region]
650 ["Allow stacked expansions "
651 (setq yas-triggers-in-field
652 (not yas-triggers-in-field))
653 :help "If non-nil allow snippets to be triggered inside other snippet fields"
654 :style toggle :selected yas-triggers-in-field]
655 ["Revive snippets on undo "
656 (setq yas-snippet-revival
657 (not yas-snippet-revival))
658 :help "If non-nil allow snippets to become active again after undo"
659 :style toggle :selected yas-snippet-revival]
662 (not yas-good-grace))
663 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
664 :style toggle :selected yas-good-grace]
667 ["Load snippets..." yas-load-directory
668 :help "Load snippets from a specific directory"]
669 ["Reload everything" yas-reload-all
670 :help "Cleanup stuff, reload snippets, rebuild menus"]
672 :help "Display some information about YASnippet"]))
674 (defvar yas--extra-modes nil
675 "An internal list of modes for which to also lookup snippets.
677 This variable probably makes more sense as buffer-local, so
678 ensure your use `make-local-variable' when you set it.")
679 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.8.1")
681 (defvar yas--tables (make-hash-table)
682 "A hash table of mode symbols to `yas--table' objects.")
684 (defvar yas--parents (make-hash-table)
685 "A hash table of mode symbols do lists of direct parent mode symbols.
687 This list is populated when reading the \".yas-parents\" files
688 found when traversing snippet directories with
689 `yas-load-directory'.
691 There might be additional parenting information stored in the
692 `derived-mode-parent' property of some mode symbols, but that is
695 (defvar yas--direct-keymaps (list)
696 "Keymap alist supporting direct snippet keybindings.
698 This variable is placed in `emulation-mode-map-alists'.
700 Its elements looks like (TABLE-NAME . KEYMAP). They're
701 instantiated on `yas-reload-all' but KEYMAP is added to only when
702 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
703 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
704 defined direct keybindings to the command
705 `yas-expand-from-keymap' which then which snippet to expand.")
707 (defun yas-direct-keymaps-reload ()
708 "Force reload the direct keybinding for active snippet tables."
710 (setq yas--direct-keymaps nil)
711 (maphash #'(lambda (name table)
712 (push (cons (intern (format "yas--direct-%s" name))
713 (yas--table-direct-keymap table))
714 yas--direct-keymaps))
717 (defun yas--modes-to-activate ()
718 "Compute list of mode symbols that are active for `yas-expand'
721 (setq dfs (lambda (mode &optional explored)
725 in (cl-list* (get mode 'derived-mode-parent)
726 (ignore-errors (symbol-function mode))
727 (gethash mode yas--parents))
729 (not (memq neighbour explored))
731 append (funcall dfs neighbour explored)))))
732 (remove-duplicates (append yas--extra-modes
733 (funcall dfs major-mode)))))
735 (defvar yas-minor-mode-hook nil
736 "Hook run when `yas-minor-mode' is turned on.")
739 (define-minor-mode yas-minor-mode
740 "Toggle YASnippet mode.
742 When YASnippet mode is enabled, `yas-expand', normally bound to
743 the TAB key, expands snippets of code depending on the major
746 With no argument, this command toggles the mode.
747 positive prefix argument turns on the mode.
748 Negative prefix argument turns off the mode.
751 \\{yas-minor-mode-map}"
753 ;; The indicator for the mode line.
756 (cond (yas-minor-mode
757 ;; Install the direct keymaps in `emulation-mode-map-alists'
758 ;; (we use `add-hook' even though it's not technically a hook,
759 ;; but it works). Then define variables named after modes to
760 ;; index `yas--direct-keymaps'.
762 ;; Also install the post-command-hook.
764 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
765 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
766 ;; Set the `yas--direct-%s' vars for direct keymap expansion
768 (dolist (mode (yas--modes-to-activate))
769 (let ((name (intern (format "yas--direct-%s" mode))))
770 (set-default name nil)
771 (set (make-local-variable name) t)))
774 (yas--load-pending-jits))
776 ;; Uninstall the direct keymaps and the post-command hook
778 (remove-hook 'post-command-hook 'yas--post-command-handler t)
779 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
781 (defun yas-activate-extra-mode (mode)
782 "Activates the snippets for the given `mode' in the buffer.
784 The function can be called in the hook of a minor mode to
785 activate snippets associated with that mode."
789 (maphash (lambda (k _)
790 (setq modes (cons (list k) modes)))
792 (setq symbol (completing-read
793 "Activate mode: " modes nil t))
795 (when (not (string= "" symbol))
798 (add-to-list (make-local-variable 'yas--extra-modes) mode)
799 (yas--load-pending-jits)))
801 (defun yas-deactivate-extra-mode (mode)
802 "Deactivates the snippets for the given `mode' in the buffer."
806 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
807 (set (make-local-variable 'yas--extra-modes)
811 (defvar yas-dont-activate '(minibufferp)
812 "If non-nil don't let `yas-global-mode' affect some buffers.
814 If a function of zero arguments, then its result is used.
816 If a list of functions, then all functions must return nil to
817 activate yas for this buffer.
819 In Emacsen <= 23, this variable is buffer-local. Because
820 `yas-minor-mode-on' is called by `yas-global-mode' after
821 executing the buffer's major mode hook, setting this variable
822 there is an effective way to define exceptions to the \"global\"
823 activation behaviour.
825 In Emacsen > 23, only the global value is used. To define
826 per-mode exceptions to the \"global\" activation behaviour, call
827 `yas-minor-mode' with a negative argument directily in the major
829 (unless (> emacs-major-version 23)
831 (make-variable-buffer-local 'yas-dont-activate)))
834 (defun yas-minor-mode-on ()
835 "Turn on YASnippet minor mode.
837 Honour `yas-dont-activate', which see."
839 ;; Check `yas-dont-activate'
840 (unless (cond ((functionp yas-dont-activate)
841 (funcall yas-dont-activate))
842 ((consp yas-dont-activate)
843 (some #'funcall yas-dont-activate))
848 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
852 (defun yas--global-mode-reload-with-jit-maybe ()
853 "Run `yas-reload-all' when `yas-global-mode' is on."
854 (when yas-global-mode (yas-reload-all)))
856 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
861 (defvar yas--font-lock-keywords
862 (append '(("^#.*$" . font-lock-comment-face))
863 lisp-font-lock-keywords-2
865 (0 font-lock-keyword-face)
866 (1 font-lock-string-face t))
868 (0 font-lock-keyword-face)
869 (1 font-lock-warning-face t))
870 ("${" . font-lock-keyword-face)
871 ("$[0-9]+?" . font-lock-preprocessor-face)
872 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
874 (0 font-lock-keyword-face)))))
876 (defvar snippet-mode-map
877 (let ((map (make-sparse-keymap)))
878 (easy-menu-define nil
880 "Menu used when snippet-mode is active."
882 (mapcar #'(lambda (ent)
884 (define-key map (third ent) (second ent)))
885 (vector (first ent) (second ent) t))
886 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
887 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
888 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
890 "The keymap used when `snippet-mode' is active.")
893 (define-derived-mode snippet-mode text-mode "Snippet"
894 "A mode for editing yasnippets"
895 (setq font-lock-defaults '(yas--font-lock-keywords))
896 (set (make-local-variable 'require-final-newline) nil)
897 (set (make-local-variable 'comment-start) "#")
898 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
902 ;;; Internal structs for template management
904 (defstruct (yas--template (:constructor yas--make-blank-template))
905 "A template for a snippet."
915 group ;; as dictated by the #group: directive or .yas-make-groups
916 perm-group ;; as dictated by `yas-define-menu'
920 (defun yas--populate-template (template &rest args)
921 "Helper function to populate TEMPLATE with properties."
924 (position (intern (substring (symbol-name (car args)) 1))
925 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
927 (setq args (cddr args)))
930 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
931 "A table to store snippets for a particular mode.
933 Has the following fields:
937 A symbol name normally corresponding to a major mode, but can
938 also be a pseudo major-mode to be used in
939 `yas-activate-extra-mode', for example.
943 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
944 a string or a vector, where the former is the snippet's trigger
945 and the latter means it's a direct keybinding. NAMEHASH is yet
946 another hash of (NAME . TEMPLATE) where NAME is the snippet's
947 name and TEMPLATE is a `yas--template' object.
949 `yas--table-direct-keymap'
951 A keymap for the snippets in this table that have direct
952 keybindings. This is kept in sync with the keyhash, i.e., all
953 the elements of the keyhash that are vectors appear here as
954 bindings to `yas-expand-from-keymap'.
956 `yas--table-uuidhash'
958 A hash table mapping snippets uuid's to the same `yas--template'
959 objects. A snippet uuid defaults to the snippet's name."
961 (hash (make-hash-table :test 'equal))
962 (uuidhash (make-hash-table :test 'equal))
964 (direct-keymap (make-sparse-keymap)))
966 (defun yas--get-template-by-uuid (mode uuid)
967 "Find the snippet template in MODE by its UUID."
968 (let* ((table (gethash mode yas--tables mode)))
970 (gethash uuid (yas--table-uuidhash table)))))
972 ;; Apropos storing/updating in TABLE, this works in two steps:
974 ;; 1. `yas--remove-template-by-uuid' removes any
975 ;; keyhash-namehash-template mappings from TABLE, grabbing the
976 ;; snippet by its uuid. Also removes mappings from TABLE's
977 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
978 ;; of potentially stale menu bindings right?.)
980 ;; 2. `yas--add-template' adds this all over again.
982 ;; Create a new or add to an existing keyhash-namehash mapping.
984 ;; For reference on understanding this, consider three snippet
987 ;; A: # name: The Foo
989 ;; # binding: C-c M-l
991 ;; B: # name: Mrs Foo
994 ;; C: # name: The Bar
995 ;; # binding: C-c M-l
1000 ;; keyhash namehashes(3) yas--template structs(4)
1001 ;; -----------------------------------------------------
1004 ;; "foo" ---> "The Foo" ---> [yas--template A] |
1005 ;; "Mrs Foo" ---> [yas--template B] |
1007 ;; [C-c M-l] ---> "The Foo" -------------------------/
1008 ;; "The Bar" ---> [yas--template C]
1010 ;; "baz" ---> "Baz" ---> [yas--template D]
1012 ;; Additionally, since uuid defaults to the name, we have a
1013 ;; `yas--table-uuidhash' for TABLE
1015 ;; uuidhash yas--template structs
1016 ;; -------------------------------
1017 ;; "The Foo" ---> [yas--template A]
1018 ;; "Mrs Foo" ---> [yas--template B]
1019 ;; "The Bar" ---> [yas--template C]
1020 ;; "Baz" ---> [yas--template D]
1022 ;; FIXME: the more I look at this data-structure the more I think I'm
1023 ;; stupid. There has to be an easier way (but beware lots of code
1024 ;; depends on this).
1026 (defun yas--remove-template-by-uuid (table uuid)
1027 "Remove from TABLE a template identified by UUID."
1028 (let ((template (gethash uuid (yas--table-uuidhash table))))
1030 (let* ((name (yas--template-name template))
1032 ;; Remove the name from each of the targeted namehashes
1034 (maphash #'(lambda (k v)
1035 (let ((template (gethash name v)))
1037 (eq uuid (yas--template-uuid template)))
1039 (when (zerop (hash-table-count v))
1040 (push k empty-keys)))))
1041 (yas--table-hash table))
1042 ;; Remove the namehash themselves if they've become empty
1044 (dolist (key empty-keys)
1046 (define-key (yas--table-direct-keymap table) key nil))
1047 (remhash key (yas--table-hash table)))
1049 ;; Finally, remove the uuid from the uuidhash
1051 (remhash uuid (yas--table-uuidhash table))))))
1053 (defun yas--add-template (table template)
1054 "Store in TABLE the snippet template TEMPLATE.
1056 KEY can be a string (trigger key) of a vector (direct
1058 (let ((name (yas--template-name template))
1059 (key (yas--template-key template))
1060 (keybinding (yas--template-keybinding template))
1061 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1062 (dolist (k (remove nil (list key keybinding)))
1066 (yas--table-hash table))
1068 (make-hash-table :test 'equal)
1069 (yas--table-hash table))))
1071 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1073 ;; Update TABLE's `yas--table-uuidhash'
1074 (puthash (yas--template-uuid template)
1076 (yas--table-uuidhash table))))
1078 (defun yas--update-template (table template)
1079 "Add or update TEMPLATE in TABLE.
1081 Also takes care of adding and updating to the associated menu."
1082 ;; Remove from table by uuid
1084 (yas--remove-template-by-uuid table (yas--template-uuid template))
1085 ;; Add to table again
1087 (yas--add-template table template)
1088 ;; Take care of the menu
1090 (yas--update-template-menu table template))
1092 (defun yas--update-template-menu (table template)
1093 "Update every menu-related for TEMPLATE."
1094 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1095 (key (yas--template-key template))
1096 (keybinding (yas--template-keybinding template)))
1097 ;; The snippet might have changed name or keys, so update
1098 ;; user-visible strings
1100 (unless (eq (cdr menu-binding-pair) :none)
1101 ;; the menu item name
1103 (setf (cadar menu-binding-pair) (yas--template-name template))
1104 ;; the :keys information (also visible to the user)
1105 (setf (getf (cdr (car menu-binding-pair)) :keys)
1106 (or (and keybinding (key-description keybinding))
1107 (and key (concat key yas-trigger-symbol))))))
1108 (unless (yas--template-menu-managed-by-yas-define-menu template)
1110 (yas--menu-keymap-get-create (yas--table-mode table)
1111 (mapcar #'yas--table-mode
1112 (yas--table-parents table))))
1113 (group (yas--template-group template)))
1114 ;; Remove from menu keymap
1116 (assert menu-keymap)
1117 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1119 ;; Add necessary subgroups as necessary.
1121 (dolist (subgroup group)
1122 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1123 (unless (and subgroup-keymap
1124 (keymapp subgroup-keymap))
1125 (setq subgroup-keymap (make-sparse-keymap))
1126 (define-key menu-keymap (vector (make-symbol subgroup))
1127 `(menu-item ,subgroup ,subgroup-keymap)))
1128 (setq menu-keymap subgroup-keymap)))
1130 ;; Add this entry to the keymap
1132 (define-key menu-keymap
1133 (vector (make-symbol (yas--template-uuid template)))
1134 (car (yas--template-menu-binding-pair template))))))
1136 (defun yas--namehash-templates-alist (namehash)
1137 "Return NAMEHASH as an alist."
1139 (maphash #'(lambda (k v)
1140 (push (cons k v) alist))
1144 (defun yas--fetch (table key)
1145 "Fetch templates in TABLE by KEY.
1147 Return a list of cons (NAME . TEMPLATE) where NAME is a
1148 string and TEMPLATE is a `yas--template' structure."
1149 (let* ((keyhash (yas--table-hash table))
1150 (namehash (and keyhash (gethash key keyhash))))
1152 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1155 ;;; Filtering/condition logic
1157 (defun yas--eval-condition (condition)
1164 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1168 (defun yas--filter-templates-by-condition (templates)
1169 "Filter the templates using the applicable condition.
1171 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1172 string and TEMPLATE is a `yas--template' structure.
1174 This function implements the rules described in
1175 `yas-buffer-local-condition'. See that variables documentation."
1176 (let ((requirement (yas--require-template-specific-condition-p)))
1177 (if (eq requirement 'always)
1179 (remove-if-not #'(lambda (pair)
1180 (yas--template-can-expand-p
1181 (yas--template-condition (cdr pair)) requirement))
1184 (defun yas--require-template-specific-condition-p ()
1185 "Decide if this buffer requests/requires snippet-specific
1186 conditions to filter out potential expansions."
1187 (if (eq 'always yas-buffer-local-condition)
1189 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1190 (yas--eval-condition yas-buffer-local-condition))
1191 yas-buffer-local-condition)))
1192 (when local-condition
1193 (if (eq local-condition t)
1195 (and (consp local-condition)
1196 (eq 'require-snippet-condition (car local-condition))
1197 (symbolp (cdr local-condition))
1198 (cdr local-condition)))))))
1200 (defun yas--template-can-expand-p (condition requirement)
1201 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1202 (let* ((result (or (null condition)
1203 (yas--eval-condition condition))))
1204 (cond ((eq requirement t)
1207 (eq requirement result)))))
1209 (defun yas--table-templates (table)
1212 (maphash #'(lambda (_key namehash)
1213 (maphash #'(lambda (name template)
1214 (push (cons name template) acc))
1216 (yas--table-hash table))
1217 (yas--filter-templates-by-condition acc))))
1219 (defun yas--templates-for-key-at-point ()
1220 "Find `yas--template' objects for any trigger keys preceding point.
1221 Returns (TEMPLATES START END). This function respects
1222 `yas-key-syntaxes', which see."
1224 (let ((original (point))
1225 (methods yas-key-syntaxes)
1230 (unless (eq method (car methods))
1231 ;; TRICKY: `eq'-ness test means we can only be here if
1232 ;; `method' is a function that returned `again', and hence
1233 ;; don't revert back to original position as per
1234 ;; `yas-key-syntaxes'.
1235 (goto-char original))
1236 (setq method (car methods))
1237 (cond ((stringp method)
1238 (skip-syntax-backward method)
1239 (setq methods (cdr methods)))
1241 (unless (eq (funcall method original)
1243 (setq methods (cdr methods))))
1245 (yas--warning "Warning invalid element %s in `yas-key-syntaxes'" method)))
1247 (mapcan #'(lambda (table)
1248 (yas--fetch table (buffer-substring-no-properties (point)
1250 (yas--get-snippet-tables))))
1252 (list templates (point) original)))))
1254 (defun yas--table-all-keys (table)
1255 "Get trigger keys of all active snippets in TABLE."
1257 (maphash #'(lambda (key namehash)
1258 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1260 (yas--table-hash table))
1263 (defun yas--table-mode (table)
1264 (intern (yas--table-name table)))
1267 ;;; Internal functions and macros:
1269 (defun yas--real-mode? (mode)
1270 "Try to find out if MODE is a real mode.
1272 The MODE bound to a function (like `c-mode') is considered real
1273 mode. Other well known mode like `ruby-mode' which is not part of
1274 Emacs might not bound to a function until it is loaded. So
1275 yasnippet keeps a list of modes like this to help the judgment."
1277 (find mode yas--known-modes)))
1279 (defun yas--handle-error (err)
1280 "Handle error depending on value of `yas-good-grace'."
1281 (let ((msg (yas--format "elisp error: %s" (error-message-string err))))
1282 (if yas-good-grace msg
1285 (defun yas--eval-lisp (form)
1286 "Evaluate FORM and convert the result to string."
1287 (let ((retval (catch 'yas--exception
1293 (let ((result (eval form)))
1295 (format "%s" result))))))
1296 (error (yas--handle-error err))))))
1297 (when (and (consp retval)
1298 (eq 'yas--exception (car retval)))
1299 (error (cdr retval)))
1302 (defun yas--eval-lisp-no-saves (form)
1305 (error (message "%s" (yas--handle-error err)))))
1307 (defun yas--read-lisp (string &optional nil-on-error)
1308 "Read STRING as a elisp expression and return it.
1310 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1311 return an expression that when evaluated will issue an error."
1314 (error (and (not nil-on-error)
1315 `(error (error-message-string ,err))))))
1317 (defun yas--read-keybinding (keybinding)
1318 "Read KEYBINDING as a snippet keybinding, return a vector."
1319 (when (and keybinding
1320 (not (string-match "keybinding" keybinding)))
1322 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1324 (read-kbd-macro keybinding 'need-vector))))
1327 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1328 keybinding (error-message-string err))
1331 (defun yas--table-get-create (mode)
1332 "Get or create the snippet table corresponding to MODE."
1333 (let ((table (gethash mode
1336 (setq table (yas--make-snippet-table (symbol-name mode)))
1337 (puthash mode table yas--tables)
1338 (push (cons (intern (format "yas--direct-%s" mode))
1339 (yas--table-direct-keymap table))
1340 yas--direct-keymaps))
1343 (defun yas--get-snippet-tables ()
1344 "Get snippet tables for current buffer.
1346 Return a list of `yas--table' objects. The list of modes to
1347 consider is returned by `yas--modes-to-activate'"
1349 (mapcar #'(lambda (name)
1350 (gethash name yas--tables))
1351 (yas--modes-to-activate))))
1353 (defun yas--menu-keymap-get-create (mode &optional parents)
1354 "Get or create the menu keymap for MODE and its PARENTS.
1356 This may very well create a plethora of menu keymaps and arrange
1357 them all in `yas--menu-table'"
1358 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1359 (puthash mode (make-sparse-keymap) yas--menu-table))))
1360 (mapc #'yas--menu-keymap-get-create parents)
1361 (define-key yas--minor-mode-menu (vector mode)
1362 `(menu-item ,(symbol-name mode) ,menu-keymap
1363 :visible (yas--show-menu-p ',mode)))
1367 (defmacro yas--called-interactively-p (&optional kind)
1368 "A backward-compatible version of `called-interactively-p'.
1370 Optional KIND is as documented at `called-interactively-p'
1371 in GNU Emacs 24.1 or higher."
1372 (if (string< emacs-version "24.1")
1373 '(called-interactively-p)
1374 `(called-interactively-p ,kind)))
1377 ;;; Template-related and snippet loading functions
1379 (defun yas--parse-template (&optional file)
1380 "Parse the template in the current buffer.
1382 Optional FILE is the absolute file name of the file being
1385 Optional GROUP is the group where the template is to go,
1386 otherwise we attempt to calculate it from FILE.
1388 Return a snippet-definition, i.e. a list
1390 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1392 If the buffer contains a line of \"# --\" then the contents above
1393 this line are ignored. Directives can set most of these with the syntax:
1395 # directive-name : directive-value
1397 Here's a list of currently recognized directives:
1408 (goto-char (point-min))
1409 (let* ((type 'snippet)
1411 (file-name-nondirectory file)))
1417 (yas--calculate-group file)))
1421 (if (re-search-forward "^# --\n" nil t)
1422 (progn (setq template
1423 (buffer-substring-no-properties (point)
1425 (setq bound (point))
1426 (goto-char (point-min))
1427 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1428 (when (string= "uuid" (match-string-no-properties 1))
1429 (setq uuid (match-string-no-properties 2)))
1430 (when (string= "type" (match-string-no-properties 1))
1431 (setq type (if (string= "command" (match-string-no-properties 2))
1434 (when (string= "key" (match-string-no-properties 1))
1435 (setq key (match-string-no-properties 2)))
1436 (when (string= "name" (match-string-no-properties 1))
1437 (setq name (match-string-no-properties 2)))
1438 (when (string= "condition" (match-string-no-properties 1))
1439 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1440 (when (string= "group" (match-string-no-properties 1))
1441 (setq group (match-string-no-properties 2)))
1442 (when (string= "expand-env" (match-string-no-properties 1))
1443 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1445 (when (string= "binding" (match-string-no-properties 1))
1446 (setq binding (match-string-no-properties 2)))))
1448 (buffer-substring-no-properties (point-min) (point-max))))
1449 (unless (or key binding)
1450 (setq key (and file (file-name-nondirectory file))))
1451 (when (eq type 'command)
1452 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1454 (setq group (split-string group "\\.")))
1455 (list key template name condition group expand-env file binding uuid)))
1457 (defun yas--calculate-group (file)
1458 "Calculate the group for snippet file path FILE."
1459 (let* ((dominating-dir (locate-dominating-file file
1460 ".yas-make-groups"))
1461 (extra-path (and dominating-dir
1462 (replace-regexp-in-string (concat "^"
1463 (expand-file-name dominating-dir))
1465 (expand-file-name file))))
1466 (extra-dir (and extra-path
1467 (file-name-directory extra-path)))
1468 (group (and extra-dir
1469 (replace-regexp-in-string "/"
1471 (directory-file-name extra-dir)))))
1474 (defun yas--subdirs (directory &optional filep)
1475 "Return subdirs or files of DIRECTORY according to FILEP."
1476 (remove-if (lambda (file)
1477 (or (string-match "^\\."
1478 (file-name-nondirectory file))
1479 (string-match "^#.*#$"
1480 (file-name-nondirectory file))
1482 (file-name-nondirectory file))
1484 (file-directory-p file)
1485 (not (file-directory-p file)))))
1486 (directory-files directory t)))
1488 (defun yas--make-menu-binding (template)
1489 (let ((mode (yas--table-mode (yas--template-table template))))
1490 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1492 (defun yas--expand-or-visit-from-menu (mode uuid)
1493 (let* ((table (yas--table-get-create mode))
1494 (yas--current-template (and table
1495 (gethash uuid (yas--table-uuidhash table)))))
1496 (when yas--current-template
1497 (if yas-visit-from-menu
1498 (yas--visit-snippet-file-1 yas--current-template)
1499 (let ((where (if (region-active-p)
1500 (cons (region-beginning) (region-end))
1501 (cons (point) (point)))))
1502 (yas-expand-snippet (yas--template-content yas--current-template)
1505 (yas--template-expand-env yas--current-template)))))))
1507 (defun yas--key-from-desc (text)
1508 "Return a yasnippet key from a description string TEXT."
1509 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1512 ;;; Popping up for keys and templates
1514 (defun yas--prompt-for-template (templates &optional prompt)
1515 "Interactively choose a template from the list TEMPLATES.
1517 TEMPLATES is a list of `yas--template'.
1519 Optional PROMPT sets the prompt to use."
1522 (sort templates #'(lambda (t1 t2)
1523 (< (length (yas--template-name t1))
1524 (length (yas--template-name t2))))))
1525 (some #'(lambda (fn)
1526 (funcall fn (or prompt "Choose a snippet: ")
1528 #'yas--template-name))
1529 yas-prompt-functions)))
1531 (defun yas--prompt-for-keys (keys &optional prompt)
1532 "Interactively choose a template key from the list KEYS.
1534 Optional PROMPT sets the prompt to use."
1536 (some #'(lambda (fn)
1537 (funcall fn (or prompt "Choose a snippet key: ") keys))
1538 yas-prompt-functions)))
1540 (defun yas--prompt-for-table (tables &optional prompt)
1541 "Interactively choose a table from the list TABLES.
1543 Optional PROMPT sets the prompt to use."
1545 (some #'(lambda (fn)
1546 (funcall fn (or prompt "Choose a snippet table: ")
1549 yas-prompt-functions)))
1551 (defun yas-x-prompt (prompt choices &optional display-fn)
1552 "Display choices in a x-window prompt."
1553 (when (and window-system choices)
1556 (if (fboundp 'posn-at-point)
1557 (let ((x-y (posn-x-y (posn-at-point (point)))))
1558 (list (list (+ (car x-y) 10)
1563 ,@(mapcar* (lambda (c d) `(,(concat " " d) . ,c))
1565 (if display-fn (mapcar display-fn choices) choices)))))
1568 (defun yas-ido-prompt (prompt choices &optional display-fn)
1569 (when (and (fboundp 'ido-completing-read)
1570 (or (>= emacs-major-version 24)
1572 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1574 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1575 (when (fboundp 'dropdown-list)
1576 (let* ((formatted-choices
1577 (if display-fn (mapcar display-fn choices) choices))
1578 (n (dropdown-list formatted-choices)))
1579 (if n (nth n choices)
1582 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1583 (let* ((formatted-choices
1584 (if display-fn (mapcar display-fn choices) choices))
1585 (chosen (funcall (or completion-fn #'completing-read)
1586 prompt formatted-choices
1587 nil 'require-match nil nil)))
1588 (if (eq choices formatted-choices)
1590 (nth (or (position chosen formatted-choices :test #'string=) 0)
1593 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1597 ;;; Defining snippets
1598 ;; This consists of creating and registering `yas--template' objects in the
1602 (defvar yas--creating-compiled-snippets nil)
1604 (defun yas--define-snippets-1 (snippet snippet-table)
1605 "Helper for `yas-define-snippets'."
1606 ;; X) Calculate some more defaults on the values returned by
1607 ;; `yas--parse-template'.
1609 (let* ((file (seventh snippet))
1611 (name (or (third snippet)
1613 (file-name-directory file))))
1614 (condition (fourth snippet))
1615 (group (fifth snippet))
1616 (keybinding (yas--read-keybinding (eighth snippet)))
1617 (uuid (or (ninth snippet)
1619 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1620 (yas--make-blank-template))))
1621 ;; X) populate the template object
1623 (yas--populate-template template
1624 :table snippet-table
1626 :content (second snippet)
1629 :condition condition
1630 :expand-env (sixth snippet)
1631 :file (seventh snippet)
1632 :keybinding keybinding
1634 ;; X) Update this template in the appropriate table. This step
1635 ;; also will take care of adding the key indicators in the
1636 ;; templates menu entry, if any
1638 (yas--update-template snippet-table template)
1639 ;; X) Return the template
1644 (defun yas-define-snippets (mode snippets)
1645 "Define SNIPPETS for MODE.
1647 SNIPPETS is a list of snippet definitions, each taking the
1650 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1652 Within these, only KEY and TEMPLATE are actually mandatory.
1654 TEMPLATE might be a Lisp form or a string, depending on whether
1655 this is a snippet or a snippet-command.
1657 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1658 been `yas--read-lisp'-ed and will eventually be
1659 `yas--eval-lisp'-ed.
1661 The remaining elements are strings.
1663 FILE is probably of very little use if you're programatically
1666 UUID is the snippet's \"unique-id\". Loading a second snippet
1667 file with the same uuid would replace the previous snippet.
1669 You can use `yas--parse-template' to return such lists based on
1670 the current buffers contents."
1671 (if yas--creating-compiled-snippets
1673 (insert ";;; Snippet definitions:\n;;;\n")
1674 (let ((literal-snippets (list))
1676 (dolist (snippet snippets)
1677 (let ((key (nth 0 snippet))
1678 (template-content (nth 1 snippet))
1679 (name (nth 2 snippet))
1680 (condition (nth 3 snippet))
1681 (group (nth 4 snippet))
1682 (expand-env (nth 5 snippet))
1683 (file nil) ;; omit on purpose
1684 (binding (nth 7 snippet))
1685 (uuid (nth 8 snippet)))
1696 (insert (pp-to-string
1697 `(yas-define-snippets ',mode ',literal-snippets)))
1700 (let ((snippet-table (yas--table-get-create mode))
1702 (dolist (snippet snippets)
1703 (setq template (yas--define-snippets-1 snippet
1708 ;;; Loading snippets from files
1710 (defun yas--load-yas-setup-file (file)
1711 (if (not yas--creating-compiled-snippets)
1713 (load file 'noerror)
1714 (let ((elfile (concat file ".el")))
1715 (when (file-exists-p elfile)
1716 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1717 (insert-file-contents elfile)
1718 (goto-char (point-max))))))
1720 (defun yas--define-parents (mode parents)
1721 "Add PARENTS to the list of MODE's parents."
1722 (puthash mode (remove-duplicates
1724 (gethash mode yas--parents)))
1727 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1728 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1730 Below TOP-LEVEL-DIR each directory should be a mode name.
1732 With prefix argument USE-JIT do jit-loading of snippets."
1734 (list (read-directory-name "Select the root directory: " nil nil t)
1735 current-prefix-arg t))
1736 (unless yas-snippet-dirs
1737 (setq yas-snippet-dirs top-level-dir))
1738 (let ((impatient-buffers))
1739 (dolist (dir (yas--subdirs top-level-dir))
1740 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1741 (concat dir "/dummy")))
1742 (mode-sym (car major-mode-and-parents))
1743 (parents (cdr major-mode-and-parents)))
1744 ;; Attention: The parents and the menus are already defined
1745 ;; here, even if the snippets are later jit-loaded.
1747 ;; * We need to know the parents at this point since entering a
1748 ;; given mode should jit load for its parents
1749 ;; immediately. This could be reviewed, the parents could be
1750 ;; discovered just-in-time-as well
1752 ;; * We need to create the menus here to support the `full'
1753 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1755 (yas--define-parents mode-sym parents)
1756 (yas--menu-keymap-get-create mode-sym)
1757 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1758 (yas--load-directory-1 ',dir ',mode-sym))))
1760 (yas--schedule-jit mode-sym fun)
1762 ;; Look for buffers that are already in `mode-sym', and so
1763 ;; need the new snippets immediately...
1766 (cl-loop for buffer in (buffer-list)
1767 do (with-current-buffer buffer
1768 (when (eq major-mode mode-sym)
1769 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1770 (push buffer impatient-buffers)))))))
1771 ;; ...after TOP-LEVEL-DIR has been completely loaded, call
1772 ;; `yas--load-pending-jits' in these impatient buffers.
1774 (cl-loop for buffer in impatient-buffers
1775 do (with-current-buffer buffer (yas--load-pending-jits))))
1777 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1779 (defun yas--load-directory-1 (directory mode-sym)
1780 "Recursively load snippet templates from DIRECTORY."
1781 (if yas--creating-compiled-snippets
1782 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1784 (with-temp-file output-file
1785 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1787 (yas--load-directory-2 directory mode-sym)
1788 (insert (format ";;; Do not edit! File generated at %s\n"
1789 (current-time-string)))))
1791 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1792 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1793 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1794 (yas--message 2 "Loading snippet files from %s" directory)
1795 (yas--load-directory-2 directory mode-sym)))))
1797 (defun yas--load-directory-2 (directory mode-sym)
1798 ;; Load .yas-setup.el files wherever we find them
1800 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1801 (let* ((default-directory directory)
1803 ;; load the snippet files
1806 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1807 (when (file-readable-p file)
1808 (insert-file-contents file nil nil nil t)
1809 (push (yas--parse-template file)
1812 (yas-define-snippets mode-sym
1814 ;; now recurse to a lower level
1816 (dolist (subdir (yas--subdirs directory))
1817 (yas--load-directory-2 subdir
1820 (defun yas--load-snippet-dirs (&optional nojit)
1821 "Reload the directories listed in `yas-snippet-dirs' or
1822 prompt the user to select one."
1824 (if yas-snippet-dirs
1825 (dolist (directory (reverse (yas-snippet-dirs)))
1826 (cond ((file-directory-p directory)
1827 (yas-load-directory directory (not nojit))
1829 (yas--message 3 "Loaded %s" directory)
1830 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1832 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1833 (call-interactively 'yas-load-directory))
1836 (defun yas-reload-all (&optional no-jit interactive)
1837 "Reload all snippets and rebuild the YASnippet menu.
1839 When NO-JIT is non-nil force immediate reload of all known
1840 snippets under `yas-snippet-dirs', otherwise use just-in-time
1843 When called interactively, use just-in-time loading when given a
1845 (interactive (list (not current-prefix-arg) t))
1848 (snippet-editing-buffers
1849 (remove-if-not #'(lambda (buffer)
1850 (with-current-buffer buffer yas--editing-template))
1852 ;; Warn if there are buffers visiting snippets, since reloading will break
1853 ;; any on-line editing of those buffers.
1855 (when snippet-editing-buffers
1857 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1858 (mapc #'kill-buffer snippet-editing-buffers)
1859 (yas--message 1 "Aborted reload...")
1861 ;; in a non-interactive use, at least set
1862 ;; `yas--editing-template' to nil, make it guess it next time around
1863 (mapc #'(lambda (buffer)
1864 (with-current-buffer buffer
1865 (kill-local-variable 'yas--editing-template)))
1868 ;; Empty all snippet tables and parenting info
1870 (setq yas--tables (make-hash-table))
1871 (setq yas--parents (make-hash-table))
1873 ;; Before killing `yas--menu-table' use its keys to cleanup the
1874 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1875 ;; up `yas-minor-mode-map', which points to it)
1877 (maphash #'(lambda (menu-symbol _keymap)
1878 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1880 ;; Now empty `yas--menu-table' as well
1881 (setq yas--menu-table (make-hash-table))
1883 ;; Cancel all pending 'yas--scheduled-jit-loads'
1885 (setq yas--scheduled-jit-loads (make-hash-table))
1887 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1888 ;; the user to select one.
1890 (setq errors (yas--load-snippet-dirs no-jit))
1891 ;; Reload the direct keybindings
1893 (yas-direct-keymaps-reload)
1895 (run-hooks 'yas-after-reload-hook)
1896 (yas--message 3 "Reloaded everything%s...%s."
1897 (if no-jit "" " (snippets will load just-in-time)")
1898 (if errors " (some errors, check *Messages*)" "")))))
1900 (defvar yas-after-reload-hook nil
1901 "Hooks run after `yas-reload-all'.")
1903 (defun yas--load-pending-jits ()
1904 (dolist (mode (yas--modes-to-activate))
1905 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1906 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1908 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1910 (remhash mode yas--scheduled-jit-loads))))
1912 ;; (when (<= emacs-major-version 22)
1913 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1915 (defun yas--quote-string (string)
1916 "Escape and quote STRING.
1917 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1919 (replace-regexp-in-string "[\\\"]"
1925 ;;; Snippet compilation function
1927 (defun yas--initialize ()
1928 "For backward compatibility, enable `yas-minor-mode' globally."
1929 (yas-global-mode 1))
1931 (defun yas-compile-directory (top-level-dir)
1932 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1934 This works by stubbing a few functions, then calling
1935 `yas-load-directory'."
1936 (interactive "DTop level snippet directory?")
1937 (let ((yas--creating-compiled-snippets t))
1938 (yas-load-directory top-level-dir nil)))
1940 (defun yas-recompile-all ()
1941 "Compile every dir in `yas-snippet-dirs'."
1943 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1949 (defvar yas--scheduled-jit-loads (make-hash-table)
1950 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1952 (defun yas--schedule-jit (mode fun)
1953 (push fun (gethash mode yas--scheduled-jit-loads)))
1957 ;;; Some user level functions
1961 (message (concat "yasnippet (version "
1963 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1966 ;;; Apropos snippet menu:
1968 ;; The snippet menu keymaps are store by mode in hash table called
1969 ;; `yas--menu-table'. They are linked to the main menu in
1970 ;; `yas--menu-keymap-get-create' and are initially created empty,
1971 ;; reflecting the table hierarchy.
1973 ;; They can be populated in two mutually exclusive ways: (1) by
1974 ;; reading `yas--template-group', which in turn is populated by the "#
1975 ;; group:" directives of the snippets or the ".yas-make-groups" file
1976 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1977 ;; menu structure based on snippets uuids.
1979 ;; Both situations are handled in `yas--update-template-menu', which
1980 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1981 ;; that can tell between the two situations.
1985 ;; * if `yas-define-menu' is used it must run before
1986 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1987 ;; duplicate entries. The `yas--template' objects are created in
1988 ;; `yas-define-menu', holding nothing but the menu entry,
1989 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1990 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1991 ;; part is then stored in the menu keymap itself which make the item
1992 ;; appear to the user. These limitations could probably be revised.
1994 ;; * The `yas--template-perm-group' slot is only used in
1995 ;; `yas-describe-tables'.
1997 (defun yas--template-menu-binding-pair-get-create (template &optional type)
1998 "Get TEMPLATE's menu binding or assign it a new one.
2000 TYPE may be `:stay', signaling this menu binding should be
2001 static in the menu."
2002 (or (yas--template-menu-binding-pair template)
2003 (let (;; (key (yas--template-key template))
2004 ;; (keybinding (yas--template-keybinding template))
2006 (setf (yas--template-menu-binding-pair template)
2007 (cons `(menu-item ,(or (yas--template-name template)
2008 (yas--template-uuid template))
2009 ,(yas--make-menu-binding template)
2012 (defun yas--template-menu-managed-by-yas-define-menu (template)
2013 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2014 (cdr (yas--template-menu-binding-pair template)))
2017 (defun yas--show-menu-p (mode)
2018 (cond ((eq yas-use-menu 'abbreviate)
2020 (mapcar #'(lambda (table)
2021 (yas--table-mode table))
2022 (yas--get-snippet-tables))))
2025 (defun yas--delete-from-keymap (keymap uuid)
2026 "Recursively delete items with UUID from KEYMAP and its submenus."
2028 ;; XXX: This used to skip any submenus named \"parent mode\"
2030 ;; First of all, recursively enter submenus, i.e. the tree is
2031 ;; searched depth first so that stale submenus can be found in the
2034 (mapc #'(lambda (item)
2035 (when (and (listp (cdr item))
2036 (keymapp (third (cdr item))))
2037 (yas--delete-from-keymap (third (cdr item)) uuid)))
2039 ;; Set the uuid entry to nil
2041 (define-key keymap (vector (make-symbol uuid)) nil)
2042 ;; Destructively modify keymap
2044 (setcdr keymap (delete-if #'(lambda (item)
2045 (or (null (cdr item))
2046 (and (keymapp (third (cdr item)))
2047 (null (cdr (third (cdr item)))))))
2050 (defun yas-define-menu (mode menu &optional omit-items)
2051 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2053 MENU is a list, its elements can be:
2055 - (yas-item UUID) : Creates an entry the snippet identified with
2056 UUID. The menu entry for a snippet thus identified is
2057 permanent, i.e. it will never move (be reordered) in the menu.
2059 - (yas-separator) : Creates a separator
2061 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2062 SUBMENU has the same form as MENU. NAME is also added to the
2063 list of groups of the snippets defined thereafter.
2065 OMIT-ITEMS is a list of snippet uuid's that will always be
2066 omitted from MODE's menu, even if they're manually loaded."
2067 (let* ((table (yas--table-get-create mode))
2068 (hash (yas--table-uuidhash table)))
2069 (yas--define-menu-1 table
2070 (yas--menu-keymap-get-create mode)
2073 (dolist (uuid omit-items)
2074 (let ((template (or (gethash uuid hash)
2075 (yas--populate-template (puthash uuid
2076 (yas--make-blank-template)
2080 (setf (yas--template-menu-binding-pair template) (cons nil :none))))))
2082 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2083 "Helper for `yas-define-menu'."
2084 (dolist (e (reverse menu))
2085 (cond ((eq (first e) 'yas-item)
2086 (let ((template (or (gethash (second e) uuidhash)
2087 (yas--populate-template (puthash (second e)
2088 (yas--make-blank-template)
2091 :perm-group group-list
2092 :uuid (second e)))))
2093 (define-key menu-keymap (vector (gensym))
2094 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2095 ((eq (first e) 'yas-submenu)
2096 (let ((subkeymap (make-sparse-keymap)))
2097 (define-key menu-keymap (vector (gensym))
2098 `(menu-item ,(second e) ,subkeymap))
2099 (yas--define-menu-1 table
2103 (append group-list (list (second e))))))
2104 ((eq (first e) 'yas-separator)
2105 (define-key menu-keymap (vector (gensym))
2106 '(menu-item "----")))
2108 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2110 (defun yas--define (mode key template &optional name condition group)
2111 "Define a snippet. Expanding KEY into TEMPLATE.
2113 NAME is a description to this template. Also update the menu if
2114 `yas-use-menu' is t. CONDITION is the condition attached to
2115 this snippet. If you attach a condition to a snippet, then it
2116 will only be expanded when the condition evaluated to non-nil."
2117 (yas-define-snippets mode
2118 (list (list key template name condition group))))
2120 (defun yas-hippie-try-expand (first-time?)
2121 "Integrate with hippie expand.
2123 Just put this function in `hippie-expand-try-functions-list'."
2124 (when yas-minor-mode
2125 (if (not first-time?)
2126 (let ((yas-fallback-behavior 'return-nil))
2132 ;;; Apropos condition-cache:
2137 (defvar yas--condition-cache-timestamp nil)
2138 (defmacro yas-define-condition-cache (func doc &rest body)
2139 "Define a function FUNC with doc DOC and body BODY.
2140 BODY is executed at most once every snippet expansion attempt, to check
2141 expansion conditions.
2143 It doesn't make any sense to call FUNC programatically."
2144 `(defun ,func () ,(if (and doc
2147 "\n\nFor use in snippets' conditions. Within each
2148 snippet-expansion routine like `yas-expand', computes actual
2149 value for the first time then always returns a cached value.")
2150 (setq body (cons doc body))
2152 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2153 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2154 (cdr timestamp-and-value)
2155 (let ((new-value (progn
2158 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2161 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2162 (defun yas-expand-from-trigger-key (&optional field)
2163 "Expand a snippet before point.
2165 If no snippet expansion is possible, fall back to the behaviour
2166 defined in `yas-fallback-behavior'.
2168 Optional argument FIELD is for non-interactive use and is an
2169 object satisfying `yas--field-p' to restrict the expansion to."
2171 (setq yas--condition-cache-timestamp (current-time))
2172 (let (templates-and-pos)
2173 (unless (and yas-expand-only-for-last-commands
2174 (not (member last-command yas-expand-only-for-last-commands)))
2175 (setq templates-and-pos (if field
2177 (narrow-to-region (yas--field-start field)
2178 (yas--field-end field))
2179 (yas--templates-for-key-at-point))
2180 (yas--templates-for-key-at-point))))
2181 (if templates-and-pos
2182 (yas--expand-or-prompt-for-template (first templates-and-pos)
2183 (second templates-and-pos)
2184 (third templates-and-pos))
2187 (defun yas-expand-from-keymap ()
2188 "Directly expand some snippets, searching `yas--direct-keymaps'.
2190 If expansion fails, execute the previous binding for this key"
2192 (setq yas--condition-cache-timestamp (current-time))
2193 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2194 (length (this-command-keys))
2196 (templates (mapcan #'(lambda (table)
2197 (yas--fetch table vec))
2198 (yas--get-snippet-tables))))
2200 (yas--expand-or-prompt-for-template templates)
2201 (let ((yas-fallback-behavior 'call-other-command))
2204 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2205 "Expand one of TEMPLATES from START to END.
2207 Prompt the user if TEMPLATES has more than one element, else
2208 expand immediately. Common gateway for
2209 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2210 (let ((yas--current-template (or (and (rest templates) ;; more than one
2211 (yas--prompt-for-template (mapcar #'cdr templates)))
2213 (when yas--current-template
2214 (yas-expand-snippet (yas--template-content yas--current-template)
2217 (yas--template-expand-env yas--current-template)))))
2219 ;; Apropos the trigger key and the fallback binding:
2221 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2222 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2223 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2224 ;; improve this explanation.
2226 (defun yas--fallback ()
2227 "Fallback after expansion has failed.
2229 Common gateway for `yas-expand-from-trigger-key' and
2230 `yas-expand-from-keymap'."
2231 (cond ((eq yas-fallback-behavior 'return-nil)
2234 ((eq yas-fallback-behavior 'call-other-command)
2235 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2236 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2237 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2238 (setq this-original-command beyond-yasnippet)
2239 (when beyond-yasnippet
2240 (call-interactively beyond-yasnippet))))
2241 ((and (listp yas-fallback-behavior)
2242 (cdr yas-fallback-behavior)
2243 (eq 'apply (car yas-fallback-behavior)))
2244 (if (cddr yas-fallback-behavior)
2245 (apply (cadr yas-fallback-behavior)
2246 (cddr yas-fallback-behavior))
2247 (when (commandp (cadr yas-fallback-behavior))
2248 (setq this-command (cadr yas-fallback-behavior))
2249 (call-interactively (cadr yas-fallback-behavior)))))
2251 ;; also return nil if all the other fallbacks have failed
2254 (defun yas--keybinding-beyond-yasnippet ()
2256 (let* ((yas-minor-mode nil)
2257 (yas--direct-keymaps nil)
2258 (keys (this-single-command-keys)))
2259 (or (key-binding keys t)
2260 (key-binding (yas--fallback-translate-input keys) t))))
2262 (defun yas--fallback-translate-input (keys)
2263 "Emulate `read-key-sequence', at least what I think it does.
2265 Keys should be an untranslated key vector. Returns a translated
2266 vector of keys. FIXME not thoroughly tested."
2269 (while (< i (length keys))
2271 (translated local-function-key-map))
2272 (while (and (< j (length keys))
2274 (keymapp translated))
2275 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2277 (setq retval (vconcat retval (cond ((symbolp translated)
2279 ((vectorp translated)
2282 (substring keys i j)))))
2287 ;;; Utils for snippet development:
2289 (defun yas--all-templates (tables)
2290 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2292 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2293 `yas-buffer-local-condition'"
2294 (when yas-choose-tables-first
2295 (setq tables (list (yas--prompt-for-table tables))))
2297 (if yas-choose-keys-first
2298 (let ((key (yas--prompt-for-keys
2299 (mapcan #'yas--table-all-keys tables))))
2301 (mapcan #'(lambda (table)
2302 (yas--fetch table key))
2304 (remove-duplicates (mapcan #'yas--table-templates tables)
2307 (defun yas-insert-snippet (&optional no-condition)
2308 "Choose a snippet to expand, pop-up a list of choices according
2309 to `yas-prompt-functions'.
2311 With prefix argument NO-CONDITION, bypass filtering of snippets
2314 (setq yas--condition-cache-timestamp (current-time))
2315 (let* ((yas-buffer-local-condition (or (and no-condition
2317 yas-buffer-local-condition))
2318 (templates (yas--all-templates (yas--get-snippet-tables)))
2319 (yas--current-template (and templates
2320 (or (and (rest templates) ;; more than one template for same key
2321 (yas--prompt-for-template templates))
2323 (where (if (region-active-p)
2324 (cons (region-beginning) (region-end))
2325 (cons (point) (point)))))
2326 (if yas--current-template
2327 (yas-expand-snippet (yas--template-content yas--current-template)
2330 (yas--template-expand-env yas--current-template))
2331 (yas--message 3 "No snippets can be inserted here!"))))
2333 (defun yas-visit-snippet-file ()
2334 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2336 Only success if selected snippet was loaded from a file. Put the
2337 visited file in `snippet-mode'."
2339 (let* ((yas-buffer-local-condition 'always)
2340 (templates (yas--all-templates (yas--get-snippet-tables)))
2341 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2342 (template (and templates
2343 (or (yas--prompt-for-template templates
2344 "Choose a snippet template to edit: ")
2348 (yas--visit-snippet-file-1 template)
2349 (message "No snippets tables active!"))))
2351 (defun yas--visit-snippet-file-1 (template)
2352 "Helper for `yas-visit-snippet-file'."
2353 (let ((file (yas--template-file template)))
2354 (cond ((and file (file-readable-p file))
2355 (find-file-other-window file)
2357 (set (make-local-variable 'yas--editing-template) template))
2359 (message "Original file %s no longer exists!" file))
2361 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2362 (let ((type 'snippet))
2363 (when (listp (yas--template-content template))
2364 (insert (format "# type: command\n"))
2365 (setq type 'command))
2366 (insert (format "# key: %s\n" (yas--template-key template)))
2367 (insert (format "# name: %s\n" (yas--template-name template)))
2368 (when (yas--template-keybinding template)
2369 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2370 (when (yas--template-expand-env template)
2371 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2372 (when (yas--template-condition template)
2373 (insert (format "# condition: %s\n" (yas--template-condition template))))
2375 (insert (if (eq type 'command)
2376 (pp-to-string (yas--template-content template))
2377 (yas--template-content template))))
2379 (set (make-local-variable 'yas--editing-template) template)))))
2381 (defun yas--guess-snippet-directories-1 (table)
2382 "Guess possible snippet subdirectories for TABLE."
2383 (cons (yas--table-name table)
2384 (mapcan #'(lambda (parent)
2385 (yas--guess-snippet-directories-1
2387 (yas--table-parents table))))
2389 (defun yas--guess-snippet-directories (&optional table)
2390 "Try to guess suitable directories based on the current active
2391 tables (or optional TABLE).
2393 Returns a list of elements (TABLE . DIRS) where TABLE is a
2394 `yas--table' object and DIRS is a list of all possible directories
2395 where snippets of table might exist."
2396 (let ((main-dir (replace-regexp-in-string
2398 (or (first (or (yas-snippet-dirs)
2399 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2400 (tables (or (and table
2402 (yas--get-snippet-tables))))
2403 ;; HACK! the snippet table created here is actually registered!
2405 (unless (or table (gethash major-mode yas--tables))
2406 (push (yas--table-get-create major-mode)
2409 (mapcar #'(lambda (table)
2411 (mapcar #'(lambda (subdir)
2412 (concat main-dir "/" subdir))
2413 (yas--guess-snippet-directories-1 table))))
2416 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2417 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2418 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2419 (let ((candidate (first (cdr table-and-dirs))))
2420 (unless (file-writable-p (file-name-directory candidate))
2421 (error (yas--format "%s is not writable." candidate)))
2422 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2424 (if (gethash (yas--table-mode (car table-and-dirs))
2428 (or main-table-string
2430 (yas--table-name (car table-and-dirs))))
2432 (make-directory candidate 'also-make-parents)
2433 ;; create the .yas-parents file here...
2436 (defun yas-new-snippet (&optional no-template)
2437 "Pops a new buffer for writing a snippet.
2439 Expands a snippet-writing snippet, unless the optional prefix arg
2440 NO-TEMPLATE is non-nil."
2442 (let ((guessed-directories (yas--guess-snippet-directories)))
2444 (switch-to-buffer "*new snippet*")
2446 (kill-all-local-variables)
2449 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2450 (yas--table-mode (car d)))
2451 guessed-directories))
2452 (if (and (not no-template) yas-new-snippet-default)
2453 (yas-expand-snippet yas-new-snippet-default))))
2455 (defun yas--compute-major-mode-and-parents (file)
2456 "Given FILE, find the nearest snippet directory for a given mode.
2458 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2459 representing one or more of the mode's parents.
2461 Note that MODE-SYM need not be the symbol of a real major mode,
2462 neither do the elements of PARENTS."
2463 (let* ((file-dir (and file
2464 (directory-file-name (or (some #'(lambda (special)
2465 (locate-dominating-file file special))
2469 (directory-file-name (file-name-directory file))))))
2470 (parents-file-name (concat file-dir "/.yas-parents"))
2471 (major-mode-name (and file-dir
2472 (file-name-nondirectory file-dir)))
2473 (major-mode-sym (or (and major-mode-name
2474 (intern major-mode-name))))
2475 (parents (when (file-readable-p parents-file-name)
2479 (insert-file-contents parents-file-name)
2480 (buffer-substring-no-properties (point-min)
2482 (when major-mode-sym
2483 (cons major-mode-sym (remove major-mode-sym parents)))))
2485 (defvar yas--editing-template nil
2486 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2488 (defvar yas--current-template nil
2489 "Holds the current template being expanded into a snippet.")
2491 (defvar yas--guessed-modes nil
2492 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2494 (defun yas--read-table ()
2495 "Ask user for a snippet table, help with some guessing."
2496 (let ((prompt (if (and (featurep 'ido)
2498 'ido-completing-read 'completing-read)))
2499 (unless yas--guessed-modes
2500 (set (make-local-variable 'yas--guessed-modes)
2501 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2503 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2504 (if yas--guessed-modes
2505 (first yas--guessed-modes)
2507 (mapcar #'symbol-name yas--guessed-modes)
2512 (if (first yas--guessed-modes)
2513 (symbol-name (first yas--guessed-modes)))))))
2515 (defun yas-load-snippet-buffer (table &optional interactive)
2516 "Parse and load current buffer's snippet definition into TABLE.
2518 TABLE is a symbol naming a passed to `yas--table-get-create'.
2520 When called interactively, prompt for the table name."
2521 (interactive (list (yas--read-table) t))
2523 ;; We have `yas--editing-template', this buffer's content comes from a
2524 ;; template which is already loaded and neatly positioned,...
2526 (yas--editing-template
2527 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2528 (yas--template-table yas--editing-template)))
2529 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2530 ;; value from `yas--compute-major-mode-and-parents'
2533 (unless yas--guessed-modes
2534 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2535 (let* ((table (yas--table-get-create table)))
2536 (set (make-local-variable 'yas--editing-template)
2537 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2540 (yas--message 3 "Snippet \"%s\" loaded for %s."
2541 (yas--template-name yas--editing-template)
2542 (yas--table-name (yas--template-table yas--editing-template)))))
2544 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2545 "Load the snippet with `yas-load-snippet-buffer', possibly
2546 save, then `quit-window' if saved.
2548 If the snippet is new, ask the user whether (and where) to save
2549 it. If the snippet already has a file, just save it.
2551 The prefix argument KILL is passed to `quit-window'.
2553 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2554 and `kill-buffer' instead."
2555 (interactive (list (yas--read-table) current-prefix-arg))
2556 (yas-load-snippet-buffer table t)
2558 ;; Only offer to save this if it looks like a library or new
2559 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2560 ;; which is not the first, or from an unwritable file)
2562 (not (yas--template-file yas--editing-template))
2563 (not (file-writable-p (yas--template-file yas--editing-template)))
2564 (and (listp yas-snippet-dirs)
2565 (second yas-snippet-dirs)
2566 (not (string-match (expand-file-name (first yas-snippet-dirs))
2567 (yas--template-file yas--editing-template)))))
2568 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2569 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2571 (yas--make-directory-maybe option))))
2573 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2574 (file-name-nondirectory (yas--template-file yas--editing-template)))
2575 (yas--template-name yas--editing-template))))
2576 (write-file (concat chosen "/"
2577 (read-from-minibuffer (format "File name to create in %s? " chosen)
2578 default-file-name)))
2579 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2580 (when buffer-file-name
2582 (quit-window kill)))
2584 (defun yas-tryout-snippet (&optional debug)
2585 "Test current buffer's snippet template in other buffer."
2587 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2588 (parsed (yas--parse-template))
2589 (test-mode (or (and (car major-mode-and-parent)
2590 (fboundp (car major-mode-and-parent))
2591 (car major-mode-and-parent))
2592 (first yas--guessed-modes)
2593 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2594 (yas--current-template
2597 (yas--populate-template (yas--make-blank-template)
2598 :table nil ;; no tables for ephemeral snippets
2600 :content (second parsed)
2601 :name (third parsed)
2602 :expand-env (sixth parsed)))))
2603 (cond (yas--current-template
2604 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2605 (kill-buffer (get-buffer-create buffer-name))
2606 (switch-to-buffer (get-buffer-create buffer-name))
2607 (setq buffer-undo-list nil)
2608 (condition-case nil (funcall test-mode) (error nil))
2610 (setq buffer-read-only nil)
2611 (yas-expand-snippet (yas--template-content yas--current-template)
2614 (yas--template-expand-env yas--current-template))
2616 (require 'yasnippet-debug nil t))
2617 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2619 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2621 (defun yas-active-keys ()
2622 "Return all active trigger keys for current buffer and point."
2624 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2627 (defun yas--template-fine-group (template)
2628 (car (last (or (yas--template-group template)
2629 (yas--template-perm-group template)))))
2631 (defun yas-describe-tables (&optional choose)
2632 "Display snippets for each table."
2634 (let* ((by-name-hash (and choose
2635 (y-or-n-p "Show by namehash? ")))
2636 (buffer (get-buffer-create "*YASnippet tables*"))
2637 (active-tables (yas--get-snippet-tables))
2638 (remain-tables (let ((all))
2639 (maphash #'(lambda (_k v)
2640 (unless (find v active-tables)
2644 (table-lists (list active-tables remain-tables))
2645 (original-buffer (current-buffer))
2647 (yas--condition-cache-timestamp (current-time)))
2648 (with-current-buffer buffer
2649 (setq buffer-read-only nil)
2651 (cond ((not by-name-hash)
2652 (insert "YASnippet tables: \n")
2653 (while (and table-lists
2655 (dolist (table (car table-lists))
2656 (yas--describe-pretty-table table original-buffer))
2657 (setq table-lists (cdr table-lists))
2659 (yas--create-snippet-xrefs)
2660 (display-buffer buffer)
2661 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2662 (yas--create-snippet-xrefs)
2666 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2667 (dolist (table (append active-tables remain-tables))
2668 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2670 (maphash #'(lambda (k _v)
2672 (yas--table-hash table))
2674 (insert (format " key %s maps snippets: %s\n" key
2676 (maphash #'(lambda (k _v)
2678 (gethash key (yas--table-hash table)))
2681 (setq buffer-read-only t))
2682 (display-buffer buffer)))
2684 (defun yas--describe-pretty-table (table &optional original-buffer)
2685 (insert (format "\nSnippet table `%s'"
2686 (yas--table-name table)))
2687 (if (yas--table-parents table)
2688 (insert (format " parents: %s\n"
2689 (mapcar #'yas--table-name
2690 (yas--table-parents table))))
2692 (insert (make-string 100 ?-) "\n")
2693 (insert "group state name key binding\n")
2694 (let ((groups-hash (make-hash-table :test #'equal)))
2695 (maphash #'(lambda (_k v)
2696 (let ((group (or (yas--template-fine-group v)
2698 (when (yas--template-name v)
2700 (cons v (gethash group groups-hash))
2702 (yas--table-uuidhash table))
2704 #'(lambda (group templates)
2705 (setq group (truncate-string-to-width group 25 0 ? "..."))
2706 (insert (make-string 100 ?-) "\n")
2707 (dolist (p templates)
2708 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2712 (setq group (make-string (length group) ? ))))
2713 (condition-string (let ((condition (yas--template-condition p)))
2716 (with-current-buffer original-buffer
2717 (if (yas--eval-condition condition)
2722 (insert condition-string " ")
2724 (if (string-match "\\.\\.\\.$" name)
2728 (insert (truncate-string-to-width (or (yas--template-key p) "")
2730 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2737 ;;; User convenience functions, for using in `yas-key-syntaxes'
2739 (defun yas-try-key-from-whitespace (_start-point)
2740 "As `yas-key-syntaxes' element, look for whitespace delimited key.
2742 A newline will be considered whitespace even if the mode syntax
2743 marks it as something else (typically comment ender)."
2744 (skip-chars-backward "^[:space:]\n"))
2746 (defun yas-shortest-key-until-whitespace (_start-point)
2747 "Like `yas-longest-key-from-whitespace' but take the shortest key."
2748 (when (/= (skip-chars-backward "^[:space:]\n" (1- (point))) 0)
2751 (defun yas-longest-key-from-whitespace (start-point)
2752 "As `yas-key-syntaxes' element, look for longest key between point and whitespace.
2754 A newline will be considered whitespace even if the mode syntax
2755 marks it as something else (typically comment ender)."
2756 (if (= (point) start-point)
2757 (yas-try-key-from-whitespace start-point)
2759 (unless (<= start-point (1+ (point)))
2764 ;;; User convenience functions, for using in snippet definitions
2766 (defvar yas-modified-p nil
2767 "Non-nil if field has been modified by user or transformation.")
2769 (defvar yas-moving-away-p nil
2770 "Non-nil if user is about to exit field.")
2772 (defvar yas-text nil
2773 "Contains current field text.")
2775 (defun yas-substr (str pattern &optional subexp)
2776 "Search PATTERN in STR and return SUBEXPth match.
2778 If found, the content of subexp group SUBEXP (default 0) is
2779 returned, or else the original STR will be returned."
2780 (let ((grp (or subexp 0)))
2782 (if (string-match pattern str)
2783 (match-string-no-properties grp str)
2786 (defun yas-choose-value (&rest possibilities)
2787 "Prompt for a string in POSSIBILITIES and return it.
2789 The last element of POSSIBILITIES may be a list of strings."
2790 (unless (or yas-moving-away-p
2792 (let* ((last-link (last possibilities))
2793 (last-elem (car last-link)))
2794 (when (listp last-elem)
2795 (setcar last-link (car last-elem))
2796 (setcdr last-link (cdr last-elem))))
2797 (some #'(lambda (fn)
2798 (funcall fn "Choose: " possibilities))
2799 yas-prompt-functions)))
2801 (defun yas-key-to-value (alist)
2802 (unless (or yas-moving-away-p
2804 (let ((key (read-key-sequence "")))
2806 (or (cdr (find key alist :key #'car :test #'string=))
2809 (defun yas-throw (text)
2810 "Throw a yas--exception with TEXT as the reason."
2811 (throw 'yas--exception (cons 'yas--exception text)))
2813 (defun yas-verify-value (possibilities)
2814 "Verify that the current field value is in POSSIBILITIES.
2816 Otherwise throw exception."
2817 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2818 (yas-throw (yas--format "Field only allows %s" possibilities))))
2820 (defun yas-field-value (number)
2821 "Get the string for field with NUMBER.
2823 Use this in primary and mirror transformations to tget."
2824 (let* ((snippet (car (yas--snippets-at-point)))
2826 (yas--snippet-find-field snippet number))))
2828 (yas--field-text-for-display field))))
2831 "Return `yas-text' if that exists and is non-empty, else nil."
2833 (not (string= "" yas-text)))
2836 (defun yas-selected-text ()
2837 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2838 (if (and yas-selected-text
2839 (not (string= "" yas-selected-text)))
2842 (defun yas--get-field-once (number &optional transform-fn)
2843 (unless yas-modified-p
2845 (funcall transform-fn (yas-field-value number))
2846 (yas-field-value number))))
2848 (defun yas-default-from-field (number)
2849 (unless yas-modified-p
2850 (yas-field-value number)))
2852 (defun yas-inside-string ()
2853 "Return non-nil if the point is inside a string according to font-lock."
2854 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2856 (defun yas-unimplemented (&optional missing-feature)
2857 (if yas--current-template
2858 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2861 (yas--visit-snippet-file-1 yas--current-template))
2862 (message "No implementation. Missing %s" (or missing-feature "something"))))
2865 ;;; Snippet expansion and field management
2867 (defvar yas--active-field-overlay nil
2868 "Overlays the currently active field.")
2870 (defvar yas--field-protection-overlays nil
2871 "Two overlays protect the current active field.")
2873 (defvar yas-selected-text nil
2874 "The selected region deleted on the last snippet expansion.")
2876 (defvar yas--start-column nil
2877 "The column where the snippet expansion started.")
2879 (make-variable-buffer-local 'yas--active-field-overlay)
2880 (make-variable-buffer-local 'yas--field-protection-overlays)
2881 (put 'yas--active-field-overlay 'permanent-local t)
2882 (put 'yas--field-protection-overlays 'permanent-local t)
2884 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2890 (id (yas--snippet-next-id) :read-only t)
2891 (control-overlay nil)
2893 ;; stacked expansion: the `previous-active-field' slot saves the
2894 ;; active field where the child expansion took place
2895 previous-active-field
2898 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2901 NUMBER is the field number.
2902 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2903 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2904 MIRRORS is a list of `yas--mirror's
2905 TRANSFORM is a lisp form.
2906 MODIFIED-P is a boolean set to true once user inputs text.
2907 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2918 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2921 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2922 TRANSFORM is a lisp form.
2923 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2924 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2925 DEPTH is a count of how many nested mirrors can affect this mirror"
2932 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2936 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2937 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2939 If there is no transform for ht field, return nil.
2941 If there is a transform but it returns nil, return the empty
2942 string iff EMPTY-ON-NIL-P is true."
2943 (let* ((yas-text (yas--field-text-for-display field))
2944 (yas-modified-p (yas--field-modified-p field))
2945 (yas-moving-away-p nil)
2946 (transform (if (yas--mirror-p field-or-mirror)
2947 (yas--mirror-transform field-or-mirror)
2948 (yas--field-transform field-or-mirror)))
2949 (start-point (if (yas--mirror-p field-or-mirror)
2950 (yas--mirror-start field-or-mirror)
2951 (yas--field-start field-or-mirror)))
2952 (transformed (and transform
2954 (goto-char start-point)
2955 (let ((ret (yas--eval-lisp transform)))
2956 (or ret (and empty-on-nil-p "")))))))
2959 (defsubst yas--replace-all (from to &optional text)
2960 "Replace all occurrences from FROM to TO.
2962 With optional string TEXT do it in that string."
2964 (replace-regexp-in-string (regexp-quote from) to text t t)
2965 (goto-char (point-min))
2966 (while (search-forward from nil t)
2967 (replace-match to t t text))))
2969 (defun yas--snippet-find-field (snippet number)
2970 (find-if #'(lambda (field)
2971 (eq number (yas--field-number field)))
2972 (yas--snippet-fields snippet)))
2974 (defun yas--snippet-sort-fields (snippet)
2975 "Sort the fields of SNIPPET in navigation order."
2976 (setf (yas--snippet-fields snippet)
2977 (sort (yas--snippet-fields snippet)
2978 #'yas--snippet-field-compare)))
2980 (defun yas--snippet-field-compare (field1 field2)
2981 "Compare FIELD1 and FIELD2.
2983 The field with a number is sorted first. If they both have a
2984 number, compare through the number. If neither have, compare
2985 through the field's start point"
2986 (let ((n1 (yas--field-number field1))
2987 (n2 (yas--field-number field2)))
2990 (or (zerop n2) (and (not (zerop n1))
2995 (< (yas--field-start field1)
2996 (yas--field-start field2))))))
2998 (defun yas--field-probably-deleted-p (snippet field)
2999 "Guess if SNIPPET's FIELD should be skipped."
3001 ;; field must be zero length
3003 (zerop (- (yas--field-start field) (yas--field-end field)))
3006 ;; 1) is a nested field and it's been modified
3008 (and (yas--field-parent-field field)
3009 (yas--field-modified-p field))
3010 ;; 2) ends just before the snippet end
3012 (and (eq field (car (last (yas--snippet-fields snippet))))
3013 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3014 ;; the field numbered 0, just before the exit marker, should
3017 (not (zerop (yas--field-number field)))))
3019 (defun yas--snippets-at-point (&optional all-snippets)
3020 "Return a sorted list of snippets at point.
3022 The most recently-inserted snippets are returned first."
3024 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3025 (overlay-get ov 'yas--snippet))
3027 (overlays-in (point-min) (point-max))
3028 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3030 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3032 (defun yas-next-field-or-maybe-expand ()
3033 "Try to expand a snippet at a key before point.
3035 Otherwise delegate to `yas-next-field'."
3037 (if yas-triggers-in-field
3038 (let ((yas-fallback-behavior 'return-nil)
3039 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3041 (unless (yas-expand-from-trigger-key active-field)
3045 (defun yas-next-field (&optional arg)
3046 "Navigate to the ARGth next field.
3048 If there's none, exit the snippet."
3052 (snippet (first (yas--snippets-at-point)))
3053 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3054 (live-fields (remove-if #'(lambda (field)
3055 (and (not (eq field active-field))
3056 (yas--field-probably-deleted-p snippet field)))
3057 (yas--snippet-fields snippet)))
3058 (active-field-pos (position active-field live-fields))
3059 (target-pos (and active-field-pos (+ arg active-field-pos)))
3060 (target-field (and target-pos (nth target-pos live-fields))))
3061 ;; First check if we're moving out of a field with a transform
3063 (when (and active-field
3064 (yas--field-transform active-field))
3065 (let* ((yas-moving-away-p t)
3066 (yas-text (yas--field-text-for-display active-field))
3067 (yas-modified-p (yas--field-modified-p active-field)))
3068 ;; primary field transform: exit call to field-transform
3069 (yas--eval-lisp (yas--field-transform active-field))))
3070 ;; Now actually move...
3071 (cond ((and target-pos (>= target-pos (length live-fields)))
3072 (yas-exit-snippet snippet))
3074 (yas--move-to-field snippet target-field))
3078 (defun yas--place-overlays (snippet field)
3079 "Correctly place overlays for SNIPPET's FIELD."
3080 (yas--make-move-field-protection-overlays snippet field)
3081 (yas--make-move-active-field-overlay snippet field))
3083 (defun yas--move-to-field (snippet field)
3084 "Update SNIPPET to move to field FIELD.
3086 Also create some protection overlays"
3087 (goto-char (yas--field-start field))
3088 (yas--place-overlays snippet field)
3089 (overlay-put yas--active-field-overlay 'yas--field field)
3090 (let ((number (yas--field-number field)))
3091 ;; check for the special ${0: ...} field
3092 (if (and number (zerop number))
3094 (set-mark (yas--field-end field))
3095 (setf (yas--snippet-force-exit snippet)
3096 (or (yas--field-transform field)
3098 ;; make this field active
3099 (setf (yas--snippet-active-field snippet) field)
3100 ;; primary field transform: first call to snippet transform
3101 (unless (yas--field-modified-p field)
3102 (if (yas--field-update-display field)
3103 (yas--update-mirrors snippet)
3104 (setf (yas--field-modified-p field) nil))))))
3106 (defun yas-prev-field ()
3107 "Navigate to prev field. If there's none, exit the snippet."
3109 (yas-next-field -1))
3111 (defun yas-abort-snippet (&optional snippet)
3113 (let ((snippet (or snippet
3114 (car (yas--snippets-at-point)))))
3116 (setf (yas--snippet-force-exit snippet) t))))
3118 (defun yas-exit-snippet (snippet)
3119 "Goto exit-marker of SNIPPET."
3120 (interactive (list (first (yas--snippets-at-point))))
3122 (setf (yas--snippet-force-exit snippet) t)
3123 (goto-char (if (yas--snippet-exit snippet)
3124 (yas--exit-marker (yas--snippet-exit snippet))
3125 (overlay-end (yas--snippet-control-overlay snippet))))))
3127 (defun yas-exit-all-snippets ()
3128 "Exit all snippets."
3130 (mapc #'(lambda (snippet)
3131 (yas-exit-snippet snippet)
3132 (yas--check-commit-snippet))
3133 (yas--snippets-at-point 'all-snippets)))
3136 ;;; Some low level snippet-routines:
3138 (defvar yas--inhibit-overlay-hooks nil
3139 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3141 (defmacro yas--inhibit-overlay-hooks (&rest body)
3142 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3143 (declare (indent 0))
3144 `(let ((yas--inhibit-overlay-hooks t))
3147 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3148 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3150 (defun yas--commit-snippet (snippet)
3151 "Commit SNIPPET, but leave point as it is.
3153 This renders the snippet as ordinary text."
3155 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3157 ;; Save the end of the moribund snippet in case we need to revive it
3158 ;; its original expansion.
3160 (when (and control-overlay
3161 (overlay-buffer control-overlay))
3162 (setq yas-snippet-beg (overlay-start control-overlay))
3163 (setq yas-snippet-end (overlay-end control-overlay))
3164 (delete-overlay control-overlay))
3166 (yas--inhibit-overlay-hooks
3167 (when yas--active-field-overlay
3168 (delete-overlay yas--active-field-overlay))
3169 (when yas--field-protection-overlays
3170 (mapc #'delete-overlay yas--field-protection-overlays)))
3172 ;; stacked expansion: if the original expansion took place from a
3173 ;; field, make sure we advance it here at least to
3174 ;; `yas-snippet-end'...
3176 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3177 (when (and yas-snippet-end previous-field)
3178 (yas--advance-end-maybe previous-field yas-snippet-end)))
3180 ;; Convert all markers to points,
3182 (yas--markers-to-points snippet)
3184 ;; Take care of snippet revival
3186 (if yas-snippet-revival
3187 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3189 ;; Dismember the snippet... this is useful if we get called
3190 ;; again from `yas--take-care-of-redo'....
3191 (setf (yas--snippet-fields snippet) nil)))
3193 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3195 (defun yas--safely-run-hooks (hook-var)
3196 (condition-case error
3197 (run-hooks hook-var)
3199 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3202 (defun yas--check-commit-snippet ()
3203 "Check if point exited the currently active field of the snippet.
3205 If so cleans up the whole snippet up."
3206 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3207 (snippets-left snippets)
3208 (snippet-exit-transform))
3209 (dolist (snippet snippets)
3210 (let ((active-field (yas--snippet-active-field snippet)))
3211 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3212 (cond ((or snippet-exit-transform
3213 (not (and active-field (yas--field-contains-point-p active-field))))
3214 (setq snippets-left (delete snippet snippets-left))
3215 (setf (yas--snippet-force-exit snippet) nil)
3216 (yas--commit-snippet snippet))
3218 (or (not yas--active-field-overlay)
3219 (not (overlay-buffer yas--active-field-overlay))))
3221 ;; stacked expansion: this case is mainly for recent
3222 ;; snippet exits that place us back int the field of
3226 (yas--move-to-field snippet active-field)
3227 (yas--update-mirrors snippet)))
3230 (unless (or (null snippets) snippets-left)
3231 (if snippet-exit-transform
3232 (yas--eval-lisp-no-saves snippet-exit-transform))
3233 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3235 ;; Apropos markers-to-points:
3237 ;; This was found useful for performance reasons, so that an
3238 ;; excessive number of live markers aren't kept around in the
3239 ;; `buffer-undo-list'. However, in `markers-to-points', the
3240 ;; set-to-nil markers can't simply be discarded and replaced with
3241 ;; fresh ones in `points-to-markers'. The original marker that was
3242 ;; just set to nil has to be reused.
3244 ;; This shouldn't bring horrible problems with undo/redo, but it
3247 (defun yas--markers-to-points (snippet)
3248 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3249 where POINT is the original position of the marker and MARKER is
3250 the original marker object with the position set to nil."
3251 (dolist (field (yas--snippet-fields snippet))
3252 (let ((start (marker-position (yas--field-start field)))
3253 (end (marker-position (yas--field-end field))))
3254 (set-marker (yas--field-start field) nil)
3255 (set-marker (yas--field-end field) nil)
3256 (setf (yas--field-start field) (cons start (yas--field-start field)))
3257 (setf (yas--field-end field) (cons end (yas--field-end field))))
3258 (dolist (mirror (yas--field-mirrors field))
3259 (let ((start (marker-position (yas--mirror-start mirror)))
3260 (end (marker-position (yas--mirror-end mirror))))
3261 (set-marker (yas--mirror-start mirror) nil)
3262 (set-marker (yas--mirror-end mirror) nil)
3263 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3264 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3265 (let ((snippet-exit (yas--snippet-exit snippet)))
3267 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3268 (set-marker (yas--exit-marker snippet-exit) nil)
3269 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3271 (defun yas--points-to-markers (snippet)
3272 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3274 This is done by setting MARKER to POINT with `set-marker'."
3275 (dolist (field (yas--snippet-fields snippet))
3276 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3277 (car (yas--field-start field))))
3278 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3279 (car (yas--field-end field))))
3280 (dolist (mirror (yas--field-mirrors field))
3281 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3282 (car (yas--mirror-start mirror))))
3283 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3284 (car (yas--mirror-end mirror))))))
3285 (let ((snippet-exit (yas--snippet-exit snippet)))
3287 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3288 (car (yas--exit-marker snippet-exit)))))))
3290 (defun yas--field-contains-point-p (field &optional point)
3291 (let ((point (or point
3293 (and (>= point (yas--field-start field))
3294 (<= point (yas--field-end field)))))
3296 (defun yas--field-text-for-display (field)
3297 "Return the propertized display text for field FIELD."
3298 (buffer-substring (yas--field-start field) (yas--field-end field)))
3300 (defun yas--undo-in-progress ()
3301 "True if some kind of undo is in progress."
3302 (or undo-in-progress
3303 (eq this-command 'undo)
3304 (eq this-command 'redo)))
3306 (defun yas--make-control-overlay (snippet start end)
3307 "Create the control overlay that surrounds the snippet and
3309 (let ((overlay (make-overlay start
3314 (overlay-put overlay 'keymap yas-keymap)
3315 (overlay-put overlay 'priority 100)
3316 (overlay-put overlay 'yas--snippet snippet)
3319 (defun yas-skip-and-clear-or-delete-char (&optional field)
3320 "Clears unmodified field if at field start, skips to next tab.
3322 Otherwise deletes a character normally by calling `delete-char'."
3324 (let ((field (or field
3325 (and yas--active-field-overlay
3326 (overlay-buffer yas--active-field-overlay)
3327 (overlay-get yas--active-field-overlay 'yas--field)))))
3329 (not (yas--field-modified-p field))
3330 (eq (point) (marker-position (yas--field-start field))))
3331 (yas--skip-and-clear field)
3334 (call-interactively 'delete-char)))))
3336 (defun yas--skip-and-clear (field)
3337 "Deletes the region of FIELD and sets it's modified state to t."
3338 ;; Just before skipping-and-clearing the field, mark its children
3339 ;; fields as modified, too. If the children have mirrors-in-fields
3340 ;; this prevents them from updating erroneously (we're skipping and
3343 (yas--mark-this-and-children-modified field)
3344 (delete-region (yas--field-start field) (yas--field-end field)))
3346 (defun yas--mark-this-and-children-modified (field)
3347 (setf (yas--field-modified-p field) t)
3348 (let ((fom (yas--field-next field)))
3350 (yas--fom-parent-field fom))
3351 (when (and (eq (yas--fom-parent-field fom) field)
3353 (yas--mark-this-and-children-modified fom))
3354 (setq fom (yas--fom-next fom)))))
3356 (defun yas--make-move-active-field-overlay (snippet field)
3357 "Place the active field overlay in SNIPPET's FIELD.
3359 Move the overlay, or create it if it does not exit."
3360 (if (and yas--active-field-overlay
3361 (overlay-buffer yas--active-field-overlay))
3362 (move-overlay yas--active-field-overlay
3363 (yas--field-start field)
3364 (yas--field-end field))
3365 (setq yas--active-field-overlay
3366 (make-overlay (yas--field-start field)
3367 (yas--field-end field)
3369 (overlay-put yas--active-field-overlay 'priority 100)
3370 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3371 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3372 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3373 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3374 '(yas--on-field-overlay-modification))
3375 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3376 '(yas--on-field-overlay-modification))))
3378 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3379 "Clears the field and updates mirrors, conditionally.
3381 Only clears the field if it hasn't been modified and it point it
3382 at field start. This hook doesn't do anything if an undo is in
3384 (unless (or yas--inhibit-overlay-hooks
3385 (yas--undo-in-progress))
3386 (let* ((field (overlay-get overlay 'yas--field))
3387 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3389 (yas--advance-end-maybe field (overlay-end overlay))
3391 (yas--field-update-display field))
3392 (yas--update-mirrors snippet))
3394 (when (and (not after?)
3395 (not (yas--field-modified-p field))
3396 (eq (point) (if (markerp (yas--field-start field))
3397 (marker-position (yas--field-start field))
3398 (yas--field-start field))))
3399 (yas--skip-and-clear field))
3400 (setf (yas--field-modified-p field) t))))))
3402 ;;; Apropos protection overlays:
3404 ;; These exist for nasty users who will try to delete parts of the
3405 ;; snippet outside the active field. Actual protection happens in
3406 ;; `yas--on-protection-overlay-modification'.
3408 ;; Currently this signals an error which inhibits the command. For
3409 ;; commands that move point (like `kill-line'), point is restored in
3410 ;; the `yas--post-command-handler' using a global
3411 ;; `yas--protection-violation' variable.
3413 ;; Alternatively, I've experimented with an implementation that
3414 ;; commits the snippet before actually calling `this-command'
3415 ;; interactively, and then signals an error, which is ignored. but
3416 ;; blocks all other million modification hooks. This presented some
3417 ;; problems with stacked expansion.
3419 (defun yas--make-move-field-protection-overlays (snippet field)
3420 "Place protection overlays surrounding SNIPPET's FIELD.
3422 Move the overlays, or create them if they do not exit."
3423 (let ((start (yas--field-start field))
3424 (end (yas--field-end field)))
3425 ;; First check if the (1+ end) is contained in the buffer,
3426 ;; otherwise we'll have to do a bit of cheating and silently
3427 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3428 ;; when using stacked expansion
3430 (when (< (buffer-size) end)
3432 (yas--inhibit-overlay-hooks
3433 (goto-char (point-max))
3435 ;; go on to normal overlay creation/moving
3437 (cond ((and yas--field-protection-overlays
3438 (every #'overlay-buffer yas--field-protection-overlays))
3439 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3440 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3442 (setq yas--field-protection-overlays
3443 (list (make-overlay (1- start) start nil t nil)
3444 (make-overlay end (1+ end) nil t nil)))
3445 (dolist (ov yas--field-protection-overlays)
3446 (overlay-put ov 'face 'yas--field-debug-face)
3447 (overlay-put ov 'yas--snippet snippet)
3448 ;; (overlay-put ov 'evaporate t)
3449 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3451 (defvar yas--protection-violation nil
3452 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3454 Functions in the `post-command-hook', for example
3455 `yas--post-command-handler' can check it and reset its value to
3456 nil. The variables value is the point where the violation
3459 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3460 "Signals a snippet violation, then issues error.
3462 The error should be ignored in `debug-ignored-errors'"
3463 (unless yas--inhibit-overlay-hooks
3464 (cond ((not (or after?
3465 (yas--undo-in-progress)))
3466 (setq yas--protection-violation (point))
3467 (error "Exit the snippet first!")))))
3469 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3472 ;;; Snippet expansion and "stacked" expansion:
3474 ;; Stacked expansion is when you try to expand a snippet when already
3475 ;; inside a snippet expansion.
3477 ;; The parent snippet does not run its fields modification hooks
3478 ;; (`yas--on-field-overlay-modification' and
3479 ;; `yas--on-protection-overlay-modification') while the child snippet
3480 ;; is active. This means, among other things, that the mirrors of the
3481 ;; parent snippet are not updated, this only happening when one exits
3482 ;; the child snippet.
3484 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3485 ;; bits of code in `yas-expand-snippet' and
3486 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3489 ;; This was thought to be safer in an undo/redo perspective, but
3490 ;; maybe the correct implementation is to make the globals
3491 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3492 ;; snippet-local and be active even while the child snippet is
3493 ;; running. This would mean a lot of overlay modification hooks
3494 ;; running, but if managed correctly (including overlay priorities)
3495 ;; they should account for all situations...
3497 (defun yas-expand-snippet (content &optional start end expand-env)
3498 "Expand snippet CONTENT at current point.
3500 Text between START and END will be deleted before inserting
3501 template. EXPAND-ENV is are let-style variable to value bindings
3502 considered when expanding the snippet."
3503 (run-hooks 'yas-before-expand-snippet-hook)
3506 (let* ((yas-selected-text (or yas-selected-text
3507 (and (region-active-p)
3508 (buffer-substring-no-properties (region-beginning)
3511 (and (region-active-p)
3515 (and (region-active-p)
3518 (to-delete (and start
3520 (buffer-substring-no-properties start end)))
3523 (setq yas--indent-original-column (current-column))
3524 ;; Delete the region to delete, this *does* get undo-recorded.
3526 (when (and to-delete
3528 (delete-region start end))
3530 (cond ((listp content)
3531 ;; x) This is a snippet-command
3533 (yas--eval-lisp-no-saves content))
3535 ;; x) This is a snippet-snippet :-)
3537 ;; Narrow the region down to the content, shoosh the
3538 ;; `buffer-undo-list', and create the snippet, the new
3539 ;; snippet updates its mirrors once, so we are left with
3540 ;; some plain text. The undo action for deleting this
3541 ;; plain text will get recorded at the end.
3543 ;; stacked expansion: also shoosh the overlay modification hooks
3544 (let ((buffer-undo-list t))
3545 ;; snippet creation might evaluate users elisp, which
3546 ;; might generate errors, so we have to be ready to catch
3547 ;; them mostly to make the undo information
3549 (setq yas--start-column (current-column))
3550 (yas--inhibit-overlay-hooks
3553 (eval `(let* ,expand-env
3555 (yas--snippet-create start (point))))
3557 (yas--snippet-create start (point))))))
3559 ;; stacked-expansion: This checks for stacked expansion, save the
3560 ;; `yas--previous-active-field' and advance its boundary.
3562 (let ((existing-field (and yas--active-field-overlay
3563 (overlay-buffer yas--active-field-overlay)
3564 (overlay-get yas--active-field-overlay 'yas--field))))
3565 (when existing-field
3566 (setf (yas--snippet-previous-active-field snippet) existing-field)
3567 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3569 ;; Exit the snippet immediately if no fields
3571 (unless (yas--snippet-fields snippet)
3572 (yas-exit-snippet snippet))
3574 ;; Push two undo actions: the deletion of the inserted contents of
3575 ;; the new snippet (without the "key") followed by an apply of
3576 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3578 ;; A small exception, if `yas-also-auto-indent-first-line'
3579 ;; is t and `yas--indent' decides to indent the line to a
3580 ;; point before the actual expansion point, undo would be
3581 ;; messed up. We call the early point "newstart"". case,
3582 ;; and attempt to fix undo.
3584 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3585 (end (overlay-end (yas--snippet-control-overlay snippet))))
3586 (when (< newstart start)
3587 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3588 (push (cons newstart end) buffer-undo-list)
3589 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3591 ;; Now, schedule a move to the first field
3593 (let ((first-field (car (yas--snippet-fields snippet))))
3595 (sit-for 0) ;; fix issue 125
3596 (yas--move-to-field snippet first-field)))
3597 (yas--message 3 "snippet expanded.")
3600 (defun yas--take-care-of-redo (_beg _end snippet)
3601 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3603 Meant to exit in the `buffer-undo-list'."
3604 ;; slightly optimize: this action is only needed for snippets with
3605 ;; at least one field
3606 (when (yas--snippet-fields snippet)
3607 (yas--commit-snippet snippet)))
3609 (defun yas--snippet-revive (beg end snippet)
3610 "Revives SNIPPET and creates a control overlay from BEG to END.
3612 BEG and END are, we hope, the original snippets boundaries.
3613 All the markers/points exiting existing inside SNIPPET should point
3614 to their correct locations *at the time the snippet is revived*.
3616 After revival, push the `yas--take-care-of-redo' in the
3618 ;; Reconvert all the points to markers
3620 (yas--points-to-markers snippet)
3621 ;; When at least one editable field existed in the zombie snippet,
3622 ;; try to revive the whole thing...
3624 (let ((target-field (or (yas--snippet-active-field snippet)
3625 (car (yas--snippet-fields snippet)))))
3627 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3628 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3630 (yas--move-to-field snippet target-field)
3632 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3633 buffer-undo-list))))
3635 (defun yas--snippet-create (begin end)
3636 "Create a snippet from a template inserted at BEGIN to END.
3638 Returns the newly created snippet."
3640 (narrow-to-region begin end)
3641 (let ((snippet (yas--make-snippet)))
3643 (yas--snippet-parse-create snippet)
3645 ;; Sort and link each field
3646 (yas--snippet-sort-fields snippet)
3648 ;; Create keymap overlay for snippet
3649 (setf (yas--snippet-control-overlay snippet)
3650 (yas--make-control-overlay snippet (point-min) (point-max)))
3653 (goto-char (point-max))
3658 ;;; Apropos adjacencies and "fom's":
3660 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3661 ;; recently expanded snippet, we might actually have many fields,
3662 ;; mirrors (and the snippet exit) in the very same position in the
3663 ;; buffer. Therefore we need to single-link the
3664 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3665 ;; according to their original positions in the buffer.
3667 ;; Then we have operation `yas--advance-end-maybe' and
3668 ;; `yas--advance-start-maybe', which conditionally push the starts and
3669 ;; ends of these foms down the chain.
3671 ;; This allows for like the printf with the magic ",":
3673 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3674 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3676 (defun yas--fom-start (fom)
3677 (cond ((yas--field-p fom)
3678 (yas--field-start fom))
3679 ((yas--mirror-p fom)
3680 (yas--mirror-start fom))
3682 (yas--exit-marker fom))))
3684 (defun yas--fom-end (fom)
3685 (cond ((yas--field-p fom)
3686 (yas--field-end fom))
3687 ((yas--mirror-p fom)
3688 (yas--mirror-end fom))
3690 (yas--exit-marker fom))))
3692 (defun yas--fom-next (fom)
3693 (cond ((yas--field-p fom)
3694 (yas--field-next fom))
3695 ((yas--mirror-p fom)
3696 (yas--mirror-next fom))
3698 (yas--exit-next fom))))
3700 (defun yas--fom-parent-field (fom)
3701 (cond ((yas--field-p fom)
3702 (yas--field-parent-field fom))
3703 ((yas--mirror-p fom)
3704 (yas--mirror-parent-field fom))
3708 (defun yas--calculate-adjacencies (snippet)
3709 "Calculate adjacencies for fields or mirrors of SNIPPET.
3711 This is according to their relative positions in the buffer, and
3712 has to be called before the $-constructs are deleted."
3713 (let* ((fom-set-next-fom
3714 (lambda (fom nextfom)
3715 (cond ((yas--field-p fom)
3716 (setf (yas--field-next fom) nextfom))
3717 ((yas--mirror-p fom)
3718 (setf (yas--mirror-next fom) nextfom))
3720 (setf (yas--exit-next fom) nextfom)))))
3723 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3724 (yas--mirror-p fom2)
3725 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3726 (link-foms fom-set-next-fom))
3727 ;; make some yas--field, yas--mirror and yas--exit soup
3729 (when (yas--snippet-exit snippet)
3730 (push (yas--snippet-exit snippet) soup))
3731 (dolist (field (yas--snippet-fields snippet))
3733 (dolist (mirror (yas--field-mirrors field))
3734 (push mirror soup)))
3736 (sort soup compare-fom-begs))
3738 (reduce link-foms soup)))))
3740 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3741 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3743 Use the tightest containing field if more than one field contains
3744 the mirror. Intended to be called *before* the dollar-regions are
3746 (let ((min (point-min))
3748 (dolist (field (yas--snippet-fields snippet))
3749 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3750 (<= (yas--mirror-end mirror) (yas--field-end field))
3751 (< min (yas--field-start field))
3752 (< (yas--field-end field) max))
3753 (setq min (yas--field-start field)
3754 max (yas--field-end field))
3755 (setf (yas--mirror-parent-field mirror) field)))))
3757 (defun yas--advance-end-maybe (fom newend)
3758 "Maybe advance FOM's end to NEWEND if it needs it.
3762 * call `yas--advance-start-maybe' on FOM's next fom.
3764 * in case FOM is field call `yas--advance-end-maybe' on its parent
3767 Also, if FOM is an exit-marker, always call
3768 `yas--advance-start-maybe' on its next fom. This is because
3769 exit-marker have identical start and end markers."
3770 (cond ((and fom (< (yas--fom-end fom) newend))
3771 (set-marker (yas--fom-end fom) newend)
3772 (yas--advance-start-maybe (yas--fom-next fom) newend)
3773 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3775 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3777 (defun yas--advance-start-maybe (fom newstart)
3778 "Maybe advance FOM's start to NEWSTART if it needs it.
3780 If it does, also call `yas--advance-end-maybe' on FOM."
3781 (when (and fom (< (yas--fom-start fom) newstart))
3782 (set-marker (yas--fom-start fom) newstart)
3783 (yas--advance-end-maybe fom newstart)))
3785 (defun yas--advance-end-of-parents-maybe (field newend)
3786 "Like `yas--advance-end-maybe' but for parent fields.
3788 Only works for fields and doesn't care about the start of the
3789 next FOM. Works its way up recursively for parents of parents."
3791 (< (yas--field-end field) newend))
3792 (set-marker (yas--field-end field) newend)
3793 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3795 (defvar yas--dollar-regions nil
3796 "When expanding the snippet the \"parse-create\" functions add
3797 cons cells to this var.")
3799 (defvar yas--backquote-markers-and-strings nil
3800 "List of (MARKER . STRING) marking where the values from
3801 backquoted Lisp expressions should be inserted at the end of
3804 (defun yas--snippet-parse-create (snippet)
3805 "Parse a recently inserted snippet template, creating all
3806 necessary fields, mirrors and exit points.
3808 Meant to be called in a narrowed buffer, does various passes"
3809 (let ((parse-start (point)))
3810 ;; Reset the yas--dollar-regions
3812 (setq yas--dollar-regions nil)
3813 ;; protect just the backquotes
3815 (yas--protect-escapes nil '(?`))
3816 ;; replace all backquoted expressions
3818 (goto-char parse-start)
3819 (yas--save-backquotes)
3820 ;; protect escaped characters
3822 (yas--protect-escapes)
3823 ;; parse fields with {}
3825 (goto-char parse-start)
3826 (yas--field-parse-create snippet)
3827 ;; parse simple mirrors and fields
3829 (goto-char parse-start)
3830 (yas--simple-mirror-parse-create snippet)
3831 ;; parse mirror transforms
3833 (goto-char parse-start)
3834 (yas--transform-mirror-parse-create snippet)
3835 ;; calculate adjacencies of fields and mirrors
3837 (yas--calculate-adjacencies snippet)
3838 ;; Delete $-constructs
3840 (save-restriction (widen) (yas--delete-regions yas--dollar-regions))
3841 ;; restore backquoted expression values
3843 (yas--restore-backquotes)
3846 (goto-char parse-start)
3847 (yas--restore-escapes)
3848 ;; update mirrors for the first time
3850 (yas--update-mirrors snippet)
3851 ;; indent the best we can
3853 (goto-char parse-start)
3854 (yas--indent snippet)))
3856 (defun yas--indent-according-to-mode (snippet-markers)
3857 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3858 ;;; Apropos indenting problems....
3860 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3861 ;; is available. Some implementations of these functions delete text
3862 ;; before they insert. If there happens to be a marker just after
3863 ;; the text being deleted, the insertion actually happens after the
3864 ;; marker, which misplaces it.
3866 ;; This would also happen if we had used overlays with the
3867 ;; `front-advance' property set to nil.
3869 ;; This is why I have these `trouble-markers', they are the ones at
3870 ;; they are the ones at the first non-whitespace char at the line
3871 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3872 ;; we should be at the correct to restore them to. All other
3873 ;; non-trouble-markers have been *pushed* and don't need special
3876 (goto-char (yas--real-line-beginning))
3877 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3883 (indent-according-to-mode)
3884 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3886 (mapc #'(lambda (marker)
3887 (set-marker marker (point)))
3890 (defvar yas--indent-original-column nil)
3891 (defun yas--indent (snippet)
3892 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3893 ;; Look for those $>
3895 (while (re-search-forward "$>" nil t)
3896 (delete-region (match-beginning 0) (match-end 0))
3897 (when (not (eq yas-indent-line 'auto))
3898 (yas--indent-according-to-mode snippet-markers))))
3899 ;; Now do stuff for 'fixed and 'auto
3901 (cond ((eq yas-indent-line 'fixed)
3902 (while (and (zerop (forward-line))
3903 (zerop (current-column)))
3904 (indent-to-column yas--indent-original-column)))
3905 ((eq yas-indent-line 'auto)
3906 (let ((end (set-marker (make-marker) (point-max)))
3907 (indent-first-line-p yas-also-auto-indent-first-line))
3908 (while (and (zerop (if indent-first-line-p
3911 (setq indent-first-line-p nil))
3915 (yas--indent-according-to-mode snippet-markers))))
3919 (defun yas--collect-snippet-markers (snippet)
3920 "Make a list of all the markers used by SNIPPET."
3922 (dolist (field (yas--snippet-fields snippet))
3923 (push (yas--field-start field) markers)
3924 (push (yas--field-end field) markers)
3925 (dolist (mirror (yas--field-mirrors field))
3926 (push (yas--mirror-start mirror) markers)
3927 (push (yas--mirror-end mirror) markers)))
3928 (let ((snippet-exit (yas--snippet-exit snippet)))
3929 (when (and snippet-exit
3930 (marker-buffer (yas--exit-marker snippet-exit)))
3931 (push (yas--exit-marker snippet-exit) markers)))
3934 (defun yas--real-line-beginning ()
3935 (let ((c (char-after (line-beginning-position)))
3936 (n (line-beginning-position)))
3937 (while (or (eql c ?\ )
3940 (setq c (char-after n)))
3943 (defun yas--escape-string (escaped)
3944 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3946 (defun yas--protect-escapes (&optional text escaped)
3947 "Protect all escaped characters with their numeric ASCII value.
3949 With optional string TEXT do it in string instead of buffer."
3950 (let ((changed-text text)
3951 (text-provided-p text))
3952 (mapc #'(lambda (escaped)
3954 (yas--replace-all (concat "\\" (char-to-string escaped))
3955 (yas--escape-string escaped)
3956 (when text-provided-p changed-text))))
3957 (or escaped yas--escaped-characters))
3960 (defun yas--restore-escapes (&optional text escaped)
3961 "Restore all escaped characters from their numeric ASCII value.
3963 With optional string TEXT do it in string instead of the buffer."
3964 (let ((changed-text text)
3965 (text-provided-p text))
3966 (mapc #'(lambda (escaped)
3968 (yas--replace-all (yas--escape-string escaped)
3969 (char-to-string escaped)
3970 (when text-provided-p changed-text))))
3971 (or escaped yas--escaped-characters))
3974 (defun yas--save-backquotes ()
3975 "Save all the \"`(lisp-expression)`\"-style expressions
3976 with their evaluated value into `yas--backquote-markers-and-strings'."
3977 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3978 (let ((current-string (match-string-no-properties 1)) transformed)
3979 (save-restriction (widen)
3980 (delete-region (match-beginning 0) (match-end 0)))
3981 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3982 (goto-char (match-beginning 0))
3984 (let ((marker (make-marker)))
3987 (insert "Y") ;; quite horrendous, I love it :)
3988 (set-marker marker (point))
3990 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3992 (defun yas--restore-backquotes ()
3993 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3994 (while yas--backquote-markers-and-strings
3995 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3996 (marker (car marker-and-string))
3997 (string (cdr marker-and-string)))
4005 (set-marker marker nil)))))
4007 (defun yas--scan-sexps (from count)
4009 (with-syntax-table (standard-syntax-table)
4010 (scan-sexps from count))
4014 (defun yas--make-marker (pos)
4015 "Create a marker at POS with nil `marker-insertion-type'."
4016 (let ((marker (set-marker (make-marker) pos)))
4017 (set-marker-insertion-type marker nil)
4020 (defun yas--field-parse-create (snippet &optional parent-field)
4021 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4023 The following count as a field:
4025 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4027 * \"${n: text$(expression)}, the same with a Lisp expression;
4028 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4030 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4032 When multiple expressions are found, only the last one counts."
4035 (while (re-search-forward yas--field-regexp nil t)
4036 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4037 (number (and (match-string-no-properties 1)
4038 (string-to-number (match-string-no-properties 1))))
4039 (brand-new-field (and real-match-end-0
4040 ;; break if on "$(" immediately
4041 ;; after the ":", this will be
4042 ;; caught as a mirror with
4044 (not (save-match-data
4045 (eq (string-match "$[ \t\n]*("
4046 (match-string-no-properties 2)) 0)))
4047 ;; allow ${0: some exit text}
4048 ;; (not (and number (zerop number)))
4049 (yas--make-field number
4050 (yas--make-marker (match-beginning 2))
4051 (yas--make-marker (1- real-match-end-0))
4053 (when brand-new-field
4054 (goto-char real-match-end-0)
4055 (push (cons (1- real-match-end-0) real-match-end-0)
4056 yas--dollar-regions)
4057 (push (cons (match-beginning 0) (match-beginning 2))
4058 yas--dollar-regions)
4059 (push brand-new-field (yas--snippet-fields snippet))
4062 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4063 (goto-char (point-min))
4064 (yas--field-parse-create snippet brand-new-field)))))))
4065 ;; if we entered from a parent field, now search for the
4066 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4067 ;; primary field transformations
4071 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4072 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4073 ;; commit the primary field transformation if:
4075 ;; 1. we don't find it in yas--dollar-regions (a subnested
4076 ;; field) might have already caught it.
4078 ;; 2. we really make sure we have either two '$' or some
4079 ;; text and a '$' after the colon ':'. This is a FIXME: work
4080 ;; my regular expressions and end these ugly hacks.
4082 (when (and real-match-end-1
4083 (not (member (cons (match-beginning 0)
4085 yas--dollar-regions))
4087 (char-before (1- (match-beginning 1))))))
4088 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4090 (setf (yas--field-transform parent-field)
4091 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4092 (push (cons (match-beginning 0) real-match-end-1)
4093 yas--dollar-regions)))))))
4095 (defun yas--transform-mirror-parse-create (snippet)
4096 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4097 (while (re-search-forward yas--transform-mirror-regexp nil t)
4098 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4099 (number (string-to-number (match-string-no-properties 1)))
4101 (not (zerop number))
4102 (yas--snippet-find-field snippet number)))
4104 (and real-match-end-0
4106 (yas--make-mirror (yas--make-marker (match-beginning 0))
4107 (yas--make-marker (match-beginning 0))
4109 (yas--restore-escapes
4110 (buffer-substring-no-properties (match-beginning 2)
4111 (1- real-match-end-0))))))))
4112 (when brand-new-mirror
4113 (push brand-new-mirror
4114 (yas--field-mirrors field))
4115 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4116 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4118 (defun yas--simple-mirror-parse-create (snippet)
4119 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4120 (while (re-search-forward yas--simple-mirror-regexp nil t)
4121 (let ((number (string-to-number (match-string-no-properties 1))))
4122 (cond ((zerop number)
4124 (setf (yas--snippet-exit snippet)
4125 (yas--make-exit (yas--make-marker (match-end 0))))
4127 (goto-char (match-beginning 0))
4128 (when yas-wrap-around-region
4129 (cond (yas-selected-text
4130 (insert yas-selected-text))
4131 ((and (eq yas-wrap-around-region 'cua)
4134 (insert (prog1 (get-register ?0)
4135 (set-register ?0 nil))))))
4136 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4137 yas--dollar-regions)))
4139 (let ((field (yas--snippet-find-field snippet number)))
4141 (let ((brand-new-mirror (yas--make-mirror
4142 (yas--make-marker (match-beginning 0))
4143 (yas--make-marker (match-beginning 0))
4145 (push brand-new-mirror
4146 (yas--field-mirrors field))
4147 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4148 (push (yas--make-field number
4149 (yas--make-marker (match-beginning 0))
4150 (yas--make-marker (match-beginning 0))
4152 (yas--snippet-fields snippet))))
4153 (push (cons (match-beginning 0) (match-end 0))
4154 yas--dollar-regions))))))
4156 (defun yas--delete-regions (regions)
4157 "Sort disjuct REGIONS by start point, then delete from the back."
4158 (mapc #'(lambda (reg)
4159 (delete-region (car reg) (cdr reg)))
4162 (>= (car r1) (car r2))))))
4164 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4165 (let* ((parent (yas--mirror-parent-field mirror))
4166 (parents-mirrors (and parent
4167 (yas--field-mirrors parent))))
4168 (or (yas--mirror-depth mirror)
4169 (setf (yas--mirror-depth mirror)
4170 (cond ((memq mirror traversed)
4172 ((and parent parents-mirrors)
4174 (mapcar #'(lambda (m)
4175 (yas--calculate-mirror-depth m
4184 (defun yas--update-mirrors (snippet)
4185 "Update all the mirrors of SNIPPET."
4187 (dolist (field-and-mirror (sort
4188 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4189 ;; where F is the field that M is mirroring
4191 (mapcan #'(lambda (field)
4192 (mapcar #'(lambda (mirror)
4193 (cons field mirror))
4194 (yas--field-mirrors field)))
4195 (yas--snippet-fields snippet))
4196 ;; then sort this list so that entries with mirrors with parent
4197 ;; fields appear before. This was important for fixing #290, and
4198 ;; luckily also handles the case where a mirror in a field causes
4199 ;; another mirror to need reupdating
4201 #'(lambda (field-and-mirror1 field-and-mirror2)
4202 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4203 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4204 (let* ((field (car field-and-mirror))
4205 (mirror (cdr field-and-mirror))
4206 (parent-field (yas--mirror-parent-field mirror)))
4207 ;; before updating a mirror with a parent-field, maybe advance
4211 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4212 ;; update this mirror
4214 (yas--mirror-update-display mirror field)
4215 ;; `yas--place-overlays' is needed if the active field and
4216 ;; protected overlays have been changed because of insertions
4217 ;; in `yas--mirror-update-display'
4219 (when (eq field (yas--snippet-active-field snippet))
4220 (yas--place-overlays snippet field))))))
4222 (defun yas--mirror-update-display (mirror field)
4223 "Update MIRROR according to FIELD (and mirror transform)."
4225 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4226 (reflection (and (not (and mirror-parent-field
4227 (yas--field-modified-p mirror-parent-field)))
4228 (or (yas--apply-transform mirror field 'empty-on-nil)
4229 (yas--field-text-for-display field)))))
4230 (when (and reflection
4231 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4232 (yas--mirror-end mirror)))))
4233 (goto-char (yas--mirror-start mirror))
4234 (yas--inhibit-overlay-hooks
4235 (insert reflection))
4236 (if (> (yas--mirror-end mirror) (point))
4237 (delete-region (point) (yas--mirror-end mirror))
4238 (set-marker (yas--mirror-end mirror) (point))
4239 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4240 ;; super-special advance
4241 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4243 (defun yas--field-update-display (field)
4244 "Much like `yas--mirror-update-display', but for fields."
4245 (when (yas--field-transform field)
4246 (let ((transformed (and (not (eq (yas--field-number field) 0))
4247 (yas--apply-transform field field))))
4248 (when (and transformed
4249 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4250 (yas--field-end field)))))
4251 (setf (yas--field-modified-p field) t)
4252 (goto-char (yas--field-start field))
4253 (yas--inhibit-overlay-hooks
4254 (insert transformed)
4255 (if (> (yas--field-end field) (point))
4256 (delete-region (point) (yas--field-end field))
4257 (set-marker (yas--field-end field) (point))
4258 (yas--advance-start-maybe (yas--field-next field) (point)))
4262 ;;; Post-command hook:
4264 (defun yas--post-command-handler ()
4265 "Handles various yasnippet conditions after each command."
4266 (cond (yas--protection-violation
4267 (goto-char yas--protection-violation)
4268 (setq yas--protection-violation nil))
4269 ((eq 'undo this-command)
4271 ;; After undo revival the correct field is sometimes not
4272 ;; restored correctly, this condition handles that
4274 (let* ((snippet (car (yas--snippets-at-point)))
4275 (target-field (and snippet
4276 (find-if-not #'(lambda (field)
4277 (yas--field-probably-deleted-p snippet field))
4279 (cons (yas--snippet-active-field snippet)
4280 (yas--snippet-fields snippet)))))))
4282 (yas--move-to-field snippet target-field))))
4283 ((not (yas--undo-in-progress))
4284 ;; When not in an undo, check if we must commit the snippet
4285 ;; (user exited it).
4286 (yas--check-commit-snippet))))
4290 ;; The docstrings for some functions are generated dynamically
4291 ;; depending on the context.
4293 (put 'yas-expand 'function-documentation
4294 '(yas--expand-from-trigger-key-doc t))
4295 (defun yas--expand-from-trigger-key-doc (context)
4296 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4297 (let* ((yas-fallback-behavior (and context yas-fallback-behavior))
4298 (fallback-description
4299 (cond ((eq yas-fallback-behavior 'call-other-command)
4300 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4302 (format "call command `%s'."
4303 (pp-to-string fallback)))
4304 "do nothing (`yas-expand' doesn't shadow\nanything).")))
4305 ((eq yas-fallback-behavior 'return-nil)
4307 (t "defer to `yas-fallback-behavior' (which see)."))))
4308 (concat "Expand a snippet before point. If no snippet
4309 expansion is possible, "
4310 fallback-description
4311 "\n\nOptional argument FIELD is for non-interactive use and is an
4312 object satisfying `yas--field-p' to restrict the expansion to.")))
4314 (put 'yas-expand-from-keymap 'function-documentation
4315 '(yas--expand-from-keymap-doc t))
4316 (defun yas--expand-from-keymap-doc (context)
4317 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4318 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4319 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4320 (when (and context (eq this-command 'describe-key))
4321 (let* ((vec (this-single-command-keys))
4322 (templates (mapcan #'(lambda (table)
4323 (yas--fetch table vec))
4324 (yas--get-snippet-tables)))
4325 (yas--direct-keymaps nil)
4326 (fallback (key-binding vec)))
4327 (concat "In this case, "
4329 (concat "these snippets are bound to this key:\n"
4330 (yas--template-pretty-list templates)
4331 "\n\nIf none of these expands, "))
4333 (format "fallback `%s' will be called." (pp-to-string fallback)))
4334 "no fallback keybinding is called."))))))
4336 (defun yas--template-pretty-list (templates)
4338 (yas-buffer-local-condition 'always))
4339 (dolist (plate templates)
4340 (setq acc (concat acc "\n*) "
4341 (propertize (concat "\\\\snippet `" (car plate) "'")
4342 'yasnippet (cdr plate)))))
4345 (define-button-type 'help-snippet-def
4346 :supertype 'help-xref
4347 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4348 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4350 (defun yas--snippet-description-finish-runonce ()
4351 "Final adjustments for the help buffer when snippets are concerned."
4352 (yas--create-snippet-xrefs)
4353 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4355 (defun yas--create-snippet-xrefs ()
4357 (goto-char (point-min))
4358 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4359 (let ((template (get-text-property (match-beginning 1)
4362 (help-xref-button 1 'help-snippet-def template)
4363 (kill-region (match-end 1) (match-end 0))
4364 (kill-region (match-beginning 0) (match-beginning 1)))))))
4368 (defvar yas-verbosity 4
4369 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4371 (defun yas--message (level message &rest args)
4372 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4373 (when (> yas-verbosity level)
4374 (message "%s" (apply #'yas--format message args))))
4376 (defun yas--warning (format-control &rest format-args)
4377 (let ((msg (apply #'format format-control format-args)))
4378 (display-warning 'yasnippet msg :warning)
4379 (yas--message 1 msg)))
4381 (defun yas--format (format-control &rest format-args)
4382 (apply #'format (concat "[yas] " format-control) format-args))
4389 ;; `locate-dominating-file'
4390 ;; `region-active-p'
4392 ;; added for compatibility in emacsen < 23
4393 (unless (>= emacs-major-version 23)
4394 (unless (fboundp 'region-active-p)
4395 (defun region-active-p () (and transient-mark-mode mark-active)))
4397 (unless (fboundp 'locate-dominating-file)
4398 (defvar locate-dominating-stop-dir-regexp
4399 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4400 "Regexp of directory names which stop the search in `locate-dominating-file'.
4401 Any directory whose name matches this regexp will be treated like
4402 a kind of root directory by `locate-dominating-file' which will stop its search
4403 when it bumps into it.
4404 The default regexp prevents fruitless and time-consuming attempts to find
4405 special files in directories in which filenames are interpreted as hostnames,
4406 or mount points potentially requiring authentication as a different user.")
4408 (defun locate-dominating-file (file name)
4409 "Look up the directory hierarchy from FILE for a file named NAME.
4410 Stop at the first parent directory containing a file NAME,
4411 and return the directory. Return nil if not found."
4412 ;; We used to use the above locate-dominating-files code, but the
4413 ;; directory-files call is very costly, so we're much better off doing
4414 ;; multiple calls using the code in here.
4416 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4417 ;; `name' in /home or in /.
4418 (setq file (abbreviate-file-name file))
4421 (while (not (or root
4423 ;; FIXME: Disabled this heuristic because it is sometimes
4425 ;; As a heuristic, we stop looking up the hierarchy of
4426 ;; directories as soon as we find a directory belonging
4427 ;; to another user. This should save us from looking in
4428 ;; things like /net and /afs. This assumes that all the
4429 ;; files inside a project belong to the same user.
4430 ;; (let ((prev-user user))
4431 ;; (setq user (nth 2 (file-attributes file)))
4432 ;; (and prev-user (not (equal user prev-user))))
4433 (string-match locate-dominating-stop-dir-regexp file)))
4434 (setq try (file-exists-p (expand-file-name name file)))
4435 (cond (try (setq root file))
4436 ((equal file (setq file (file-name-directory
4437 (directory-file-name file))))
4442 ;;; Backward compatibility to yasnippet <= 0.7
4444 (defvar yas--backported-syms '(;; `defcustom's
4447 yas-prompt-functions
4449 yas-also-auto-indent-first-line
4451 yas-triggers-in-field
4452 yas-fallback-behavior
4453 yas-choose-keys-first
4454 yas-choose-tables-first
4457 yas-wrap-around-region
4460 yas-expand-only-for-last-commands
4461 yas-field-highlight-face
4463 ;; these vars can be customized as well
4469 yas-after-exit-snippet-hook
4470 yas-before-expand-snippet-hook
4471 yas-buffer-local-condition
4474 ;; prompting functions
4479 yas-completing-prompt
4482 ;; interactive functions
4487 yas-direct-keymaps-reload
4491 yas-compile-directory
4494 yas-expand-from-trigger-key
4495 yas-expand-from-keymap
4497 yas-visit-snippet-file
4499 yas-load-snippet-buffer
4502 yas-next-field-or-maybe-expand
4507 yas-exit-all-snippets
4508 yas-skip-and-clear-or-delete-char
4510 ;; symbols that I "exported" for use
4511 ;; in snippets and hookage
4528 yas-default-from-field
4531 yas-define-condition-cache
4532 yas-hippie-try-expand
4534 ;; debug definitions
4535 ;; yas-debug-snippet-vars
4536 ;; yas-exterminate-package
4539 ;; testing definitions
4540 ;; yas-should-expand
4541 ;; yas-should-not-expand
4543 ;; yas-make-file-or-dirs
4545 ;; yas-saving-variables
4546 ;; yas-call-with-snippet-dirs
4547 ;; yas-with-snippet-dirs
4549 "Backported yasnippet symbols.
4551 They are mapped to \"yas/*\" variants.")
4553 (dolist (sym yas--backported-syms)
4554 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4556 (make-obsolete-variable backported sym "yasnippet 0.8")
4557 (defvaralias backported sym))
4559 (make-obsolete backported sym "yasnippet 0.8")
4560 (defalias backported sym))))
4562 (defvar yas--exported-syms
4564 (mapatoms (lambda (atom)
4565 (if (and (or (and (boundp atom)
4566 (not (get atom 'byte-obsolete-variable)))
4568 (not (get atom 'byte-obsolete-info))))
4569 (string-match-p "^yas-[^-]" (symbol-name atom)))
4570 (push atom exported))))
4572 "Exported yasnippet symbols.
4574 i.e. the ones with \"yas-\" single dash prefix. I will try to
4575 keep them in future yasnippet versions and other elisp libraries
4576 can more or less safely rely upon them.")
4579 (provide 'yasnippet)
4581 ;;; yasnippet.el ends here
4584 ;; byte-compile-warnings: (not cl-functions)