1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2013 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
5 ;; Maintainer: João Távora <joaotavora@gmail.com>
7 ;; Package-version: 0.8.0
8 ;; X-URL: http://github.com/capitaomorte/yasnippet
9 ;; Keywords: convenience, emulation
10 ;; URL: http://github.com/capitaomorte/yasnippet
11 ;; EmacsWiki: YaSnippetMode
13 ;; This program is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; This program is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
28 ;; Basic steps to setup:
30 ;; (add-to-list 'load-path
31 ;; "~/path-to-yasnippet")
32 ;; (require 'yasnippet)
33 ;; (yas-global-mode 1)
36 ;; Interesting variables are:
40 ;; The directory where user-created snippets are to be
41 ;; stored. Can also be a list of directories. In that case,
42 ;; when used for bulk (re)loading of snippets (at startup or
43 ;; via `yas-reload-all'), directories appearing earlier in
44 ;; the list shadow other dir's snippets. Also, the first
45 ;; directory is taken as the default for storing the user's
48 ;; The deprecated `yas/root-directory' aliases this variable
49 ;; for backward-compatibility.
52 ;; Major commands are:
56 ;; Try to expand snippets before point. In `yas-minor-mode',
57 ;; this is normally bound to TAB, but you can customize it in
58 ;; `yas-minor-mode-map'.
60 ;; M-x yas-load-directory
62 ;; Prompts you for a directory hierarchy of snippets to load.
64 ;; M-x yas-activate-extra-mode
66 ;; Prompts you for an extra mode to add snippets for in the
69 ;; M-x yas-insert-snippet
71 ;; Prompts you for possible snippet expansion if that is
72 ;; possible according to buffer-local and snippet-local
73 ;; expansion conditions. With prefix argument, ignore these
76 ;; M-x yas-visit-snippet-file
78 ;; Prompts you for possible snippet expansions like
79 ;; `yas-insert-snippet', but instead of expanding it, takes
80 ;; you directly to the snippet definition's file, if it
83 ;; M-x yas-new-snippet
85 ;; Lets you create a new snippet file in the correct
86 ;; subdirectory of `yas-snippet-dirs', according to the
89 ;; M-x yas-load-snippet-buffer
91 ;; When editing a snippet, this loads the snippet. This is
92 ;; bound to "C-c C-c" while in the `snippet-mode' editing
95 ;; M-x yas-tryout-snippet
97 ;; When editing a snippet, this opens a new empty buffer,
98 ;; sets it to the appropriate major mode and inserts the
99 ;; snippet there, so you can see what it looks like. This is
100 ;; bound to "C-c C-t" while in `snippet-mode'.
102 ;; M-x yas-describe-tables
104 ;; Lists known snippets in a separate buffer. User is
105 ;; prompted as to whether only the currently active tables
106 ;; are to be displayed, or all the tables for all major
109 ;; If you have `dropdown-list' installed, you can optionally use it
110 ;; as the preferred "prompting method", putting in your .emacs file,
113 ;; (require 'dropdown-list)
114 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
116 ;; yas-completing-prompt))
118 ;; Also check out the customization group
120 ;; M-x customize-group RET yasnippet RET
122 ;; If you use the customization group to set variables
123 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
124 ;; "yasnippet.el" is present in the `load-path' *before* the
125 ;; `custom-set-variables' is executed in your .emacs file.
127 ;; For more information and detailed usage, refer to the project page:
128 ;; http://github.com/capitaomorte/yasnippet
136 (defvar yas--editing-template)
137 (defvar yas--guessed-modes)
138 (defvar yas--indent-original-column)
139 (defvar yas--scheduled-jit-loads)
141 (defvar yas-selected-text)
142 (defvar yas-verbosity)
143 (defvar yas--current-template)
146 ;;; User customizable variables
148 (defgroup yasnippet nil
149 "Yet Another Snippet extension"
152 (defvar yas--load-file-name load-file-name
153 "Store the filename that yasnippet.el was originally loaded from.")
155 (defcustom yas-snippet-dirs (remove nil
156 (list "~/.emacs.d/snippets"
157 (when yas--load-file-name
158 (concat (file-name-directory yas--load-file-name) "snippets"))))
159 "Directory or list of snippet dirs for each major mode.
161 The directory where user-created snippets are to be stored. Can
162 also be a list of directories. In that case, when used for
163 bulk (re)loading of snippets (at startup or via
164 `yas-reload-all'), directories appearing earlier in the list
165 shadow other dir's snippets. Also, the first directory is taken
166 as the default for storing the user's new snippets."
167 :type '(choice (string :tag "Single directory (string)")
168 (repeat :args (string) :tag "List of directories (strings)"))
171 :set #'(lambda (symbol new)
172 (let ((old (and (boundp symbol)
173 (symbol-value symbol))))
174 (set-default symbol new)
175 (unless (or (not (fboundp 'yas-reload-all))
179 (defun yas-snippet-dirs ()
180 "Return `yas-snippet-dirs' (which see) as a list."
181 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
183 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
185 (defcustom yas-new-snippet-default "\
186 # -*- mode: snippet -*-
188 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
189 # binding: ${4:direct-keybinding}}${5:
190 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
194 "Default snippet to use when creating a new snippet.
195 If nil, don't use any snippet."
199 (defcustom yas-prompt-functions '(yas-x-prompt
201 yas-completing-prompt
204 "Functions to prompt for keys, templates, etc interactively.
206 These functions are called with the following arguments:
208 - PROMPT: A string to prompt the user
210 - CHOICES: a list of strings or objects.
212 - optional DISPLAY-FN : A function that, when applied to each of
213 the objects in CHOICES will return a string.
215 The return value of any function you put here should be one of
216 the objects in CHOICES, properly formatted with DISPLAY-FN (if
219 - To signal that your particular style of prompting is
220 unavailable at the moment, you can also have the function return
223 - To signal that the user quit the prompting process, you can
226 (signal 'quit \"user quit!\")."
227 :type '(repeat function)
230 (defcustom yas-indent-line 'auto
231 "Controls indenting applied to a recent snippet expansion.
233 The following values are possible:
235 - `fixed' Indent the snippet to the current column;
237 - `auto' Indent each line of the snippet with `indent-according-to-mode'
239 Every other value means don't apply any snippet-side indentation
240 after expansion (the manual per-line \"$>\" indentation still
242 :type '(choice (const :tag "Nothing" nothing)
243 (const :tag "Fixed" fixed)
244 (const :tag "Auto" auto))
247 (defcustom yas-also-auto-indent-first-line nil
248 "Non-nil means also auto indent first line according to mode.
250 Naturally this is only valid when `yas-indent-line' is `auto'"
254 (defcustom yas-snippet-revival t
255 "Non-nil means re-activate snippet fields after undo/redo."
259 (defcustom yas-triggers-in-field nil
260 "If non-nil, allow stacked expansions (snippets inside snippets).
262 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
267 (defcustom yas-fallback-behavior 'call-other-command
268 "How to act when `yas-expand' does *not* expand a snippet.
270 - `call-other-command' means try to temporarily disable YASnippet
271 and call the next command bound to whatever key was used to
274 - nil or the symbol `return-nil' mean do nothing. (and
275 `yas-expand' returns nil)
277 - A Lisp form (apply COMMAND . ARGS) means interactively call
278 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
279 with ARGS as arguments."
280 :type '(choice (const :tag "Call previous command" call-other-command)
281 (const :tag "Do nothing" return-nil))
284 (defcustom yas-choose-keys-first nil
285 "If non-nil, prompt for snippet key first, then for template.
287 Otherwise prompts for all possible snippet names.
289 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
293 (defcustom yas-choose-tables-first nil
294 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
296 Otherwise, user chooses between the merging together of all
299 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
303 (defcustom yas-use-menu 'abbreviate
304 "Display a YASnippet menu in the menu bar.
306 When non-nil, submenus for each snippet table will be listed
307 under the menu \"Yasnippet\".
309 - If set to `abbreviate', only the current major-mode
310 menu and the modes set in `yas--extra-modes' are listed.
312 - If set to `full', every submenu is listed
314 - It set to nil, don't display a menu at all (this requires a
315 `yas-reload-all' call if the menu is already visible).
317 Any other non-nil value, every submenu is listed."
318 :type '(choice (const :tag "Full" full)
319 (const :tag "Abbreviate" abbreviate)
320 (const :tag "No menu" nil))
323 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
325 (char-to-string ?\x21E5))) ;; little ->| sign
327 "The text that will be used in menu to represent the trigger."
331 (defcustom yas-wrap-around-region nil
332 "If non-nil, snippet expansion wraps around selected region.
334 The wrapping occurs just before the snippet's exit marker. This
335 can be overridden on a per-snippet basis."
339 (defcustom yas-good-grace t
340 "If non-nil, don't raise errors in inline elisp evaluation.
342 An error string \"[yas] error\" is returned instead."
346 (defcustom yas-visit-from-menu nil
347 "If non-nil visit snippets's files from menu, instead of expanding them.
349 This can only work when snippets are loaded from files."
353 (defcustom yas-expand-only-for-last-commands nil
354 "List of `last-command' values to restrict tab-triggering to, or nil.
356 Leave this set at nil (the default) to be able to trigger an
357 expansion simply by placing the cursor after a valid tab trigger,
358 using whichever commands.
360 Optionally, set this to something like '(self-insert-command) if
361 you to wish restrict expansion to only happen when the last
362 letter of the snippet tab trigger was typed immediately before
363 the trigger key itself."
364 :type '(repeat function)
367 ;; Only two faces, and one of them shouldn't even be used...
369 (defface yas-field-highlight-face
370 '((t (:inherit 'region)))
371 "The face used to highlight the currently active field of a snippet"
374 (defface yas--field-debug-face
376 "The face used for debugging some overlays normally hidden"
380 ;;; User-visible variables
382 (defvar yas-keymap (let ((map (make-sparse-keymap)))
383 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
384 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
385 (define-key map [(shift tab)] 'yas-prev-field)
386 (define-key map [backtab] 'yas-prev-field)
387 (define-key map (kbd "C-g") 'yas-abort-snippet)
388 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
390 "The active keymap while a snippet expansion is in progress.")
392 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
393 "List of character syntaxes used to find a trigger key before point.
394 The list is tried in the order while scanning characters
395 backwards from point. For example, if the list is '(\"w\" \"w_\")
396 first look for trigger keys which are composed exclusively of
397 \"word\"-syntax characters, and then, if that fails, look for
398 keys which are either of \"word\" or \"symbol\"
399 syntax. Triggering after
403 will, according to the \"w\" element first try \"bar\". If that
404 isn't a trigger key, \"foo-bar\" is tried, respecting a second
407 (defvar yas-after-exit-snippet-hook
409 "Hooks to run after a snippet exited.
411 The hooks will be run in an environment where some variables bound to
414 `yas-snippet-beg' : The beginning of the region of the snippet.
416 `yas-snippet-end' : Similar to beg.
418 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
420 (defvar yas-before-expand-snippet-hook
422 "Hooks to run just before expanding a snippet.")
424 (defvar yas-buffer-local-condition
425 '(if (and (or (fourth (syntax-ppss))
426 (fifth (syntax-ppss)))
428 (eq this-command 'yas-expand-from-trigger-key))
429 '(require-snippet-condition . force-in-comment)
431 "Snippet expanding condition.
433 This variable is a Lisp form which is evaluated every time a
434 snippet expansion is attempted:
436 * If it evaluates to nil, no snippets can be expanded.
438 * If it evaluates to the a cons (require-snippet-condition
441 * Snippets bearing no \"# condition:\" directive are not
444 * Snippets bearing conditions that evaluate to nil (or
445 produce an error) won't be considered.
447 * If the snippet has a condition that evaluates to non-nil
450 * If REQUIREMENT is t, the snippet is considered
452 * If REQUIREMENT is `eq' RESULT, the snippet is
455 * Otherwise, the snippet is not considered.
457 * If it evaluates to the symbol 'always, all snippets are
458 considered for expansion, regardless of any conditions.
460 * If it evaluates to t or some other non-nil value
462 * Snippet bearing no conditions, or conditions that
463 evaluate to non-nil, are considered for expansion.
465 * Otherwise, the snippet is not considered.
467 Here's an example preventing snippets from being expanded from
468 inside comments, in `python-mode' only, with the exception of
469 snippets returning the symbol 'force-in-comment in their
472 (add-hook 'python-mode-hook
474 (setq yas-buffer-local-condition
475 '(if (python-in-string/comment)
476 '(require-snippet-condition . force-in-comment)
479 The default value is similar, it filters out potential snippet
480 expansions inside comments and string literals, unless the
481 snippet itself contains a condition that returns the symbol
482 `force-in-comment'.")
485 ;;; Internal variables
487 (defvar yas--version "0.8.0beta")
489 (defvar yas--menu-table (make-hash-table)
490 "A hash table of MAJOR-MODE symbols to menu keymaps.")
492 (defvar yas--known-modes
493 '(ruby-mode rst-mode markdown-mode)
494 "A list of mode which is well known but not part of Emacs.")
496 (defvar yas--escaped-characters
497 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
498 "List of characters which *might* need to be escaped.")
500 (defconst yas--field-regexp
501 "${\\([0-9]+:\\)?\\([^}]*\\)}"
502 "A regexp to *almost* recognize a field.")
504 (defconst yas--multi-dollar-lisp-expression-regexp
505 "$+[ \t\n]*\\(([^)]*)\\)"
506 "A regexp to *almost* recognize a \"$(...)\" expression.")
508 (defconst yas--backquote-lisp-expression-regexp
510 "A regexp to recognize a \"`lisp-expression`\" expression." )
512 (defconst yas--transform-mirror-regexp
513 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
514 "A regexp to *almost* recognize a mirror with a transform.")
516 (defconst yas--simple-mirror-regexp
518 "A regexp to recognize a simple mirror.")
520 (defvar yas--snippet-id-seed 0
521 "Contains the next id for a snippet.")
523 (defun yas--snippet-next-id ()
524 (let ((id yas--snippet-id-seed))
525 (incf yas--snippet-id-seed)
531 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
532 (defvar last-buffer-undo-list nil)
534 (defvar yas--minor-mode-menu nil
535 "Holds the YASnippet menu.")
537 (defun yas--init-minor-keymap ()
538 "Set up the `yas-minor-mode' keymap."
539 (let ((map (make-sparse-keymap)))
541 (easy-menu-define yas--minor-mode-menu
543 "Menu used when `yas-minor-mode' is active."
546 ["Expand trigger" yas-expand
547 :help "Possibly expand tab trigger before point"]
548 ["Insert at point..." yas-insert-snippet
549 :help "Prompt for an expandable snippet and expand it at point"]
550 ["New snippet..." yas-new-snippet
551 :help "Create a new snippet in an appropriate directory"]
552 ["Visit snippet file..." yas-visit-snippet-file
553 :help "Prompt for an expandable snippet and find its file"]
555 ("Snippet menu behaviour"
556 ["Visit snippets" (setq yas-visit-from-menu t)
557 :help "Visit snippets from the menu"
558 :active t :style radio :selected yas-visit-from-menu]
559 ["Expand snippets" (setq yas-visit-from-menu nil)
560 :help "Expand snippets from the menu"
561 :active t :style radio :selected (not yas-visit-from-menu)]
563 ["Show all known modes" (setq yas-use-menu 'full)
564 :help "Show one snippet submenu for each loaded table"
565 :active t :style radio :selected (eq yas-use-menu 'full)]
566 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
567 :help "Show only snippet submenus for the current active modes"
568 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
570 ["Auto" (setq yas-indent-line 'auto)
571 :help "Indent each line of the snippet with `indent-according-to-mode'"
572 :active t :style radio :selected (eq yas-indent-line 'auto)]
573 ["Fixed" (setq yas-indent-line 'fixed)
574 :help "Indent the snippet to the current column"
575 :active t :style radio :selected (eq yas-indent-line 'fixed)]
576 ["None" (setq yas-indent-line 'none)
577 :help "Don't apply any particular snippet indentation after expansion"
578 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
580 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
581 (not yas-also-auto-indent-first-line))
582 :help "When auto-indenting also, auto indent the first line menu"
583 :active (eq yas-indent-line 'auto)
584 :style toggle :selected yas-also-auto-indent-first-line]
587 ["System X-widget" (setq yas-prompt-functions
589 (remove 'yas-x-prompt
590 yas-prompt-functions)))
591 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
592 :active t :style radio :selected (eq (car yas-prompt-functions)
594 ["Dropdown-list" (setq yas-prompt-functions
595 (cons 'yas-dropdown-prompt
596 (remove 'yas-dropdown-prompt
597 yas-prompt-functions)))
598 :help "Use a special dropdown list"
599 :active t :style radio :selected (eq (car yas-prompt-functions)
600 'yas-dropdown-prompt)]
601 ["Ido" (setq yas-prompt-functions
602 (cons 'yas-ido-prompt
603 (remove 'yas-ido-prompt
604 yas-prompt-functions)))
605 :help "Use an ido-style minibuffer prompt"
606 :active t :style radio :selected (eq (car yas-prompt-functions)
608 ["Completing read" (setq yas-prompt-functions
609 (cons 'yas-completing-prompt
610 (remove 'yas-completing-prompt
611 yas-prompt-functions)))
612 :help "Use a normal minibuffer prompt"
613 :active t :style radio :selected (eq (car yas-prompt-functions)
614 'yas-completing-prompt)]
617 ["Wrap region in exit marker"
618 (setq yas-wrap-around-region
619 (not yas-wrap-around-region))
620 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
621 :style toggle :selected yas-wrap-around-region]
622 ["Allow stacked expansions "
623 (setq yas-triggers-in-field
624 (not yas-triggers-in-field))
625 :help "If non-nil allow snippets to be triggered inside other snippet fields"
626 :style toggle :selected yas-triggers-in-field]
627 ["Revive snippets on undo "
628 (setq yas-snippet-revival
629 (not yas-snippet-revival))
630 :help "If non-nil allow snippets to become active again after undo"
631 :style toggle :selected yas-snippet-revival]
634 (not yas-good-grace))
635 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
636 :style toggle :selected yas-good-grace]
639 ["Load snippets..." yas-load-directory
640 :help "Load snippets from a specific directory"]
641 ["Reload everything" yas-reload-all
642 :help "Cleanup stuff, reload snippets, rebuild menus"]
644 :help "Display some information about YASnippet"])))
646 ;; Now for the stuff that has direct keybindings
648 (define-key map [(tab)] 'yas-expand)
649 (define-key map (kbd "TAB") 'yas-expand)
650 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
651 (define-key map "\C-c&\C-n" 'yas-new-snippet)
652 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
655 (defvar yas-minor-mode-map (yas--init-minor-keymap)
656 "The keymap used when `yas-minor-mode' is active.")
658 (defvar yas--extra-modes nil
659 "An internal list of modes for which to also lookup snippets.
661 This variable probably makes more sense as buffer-local, so
662 ensure your use `make-local-variable' when you set it.")
663 (define-obsolete-variable-alias 'yas-extra-modes 'yas--extra-modes "0.8.1")
665 (defvar yas--tables (make-hash-table)
666 "A hash table of mode symbols to `yas--table' objects.")
668 (defvar yas--parents (make-hash-table)
669 "A hash table of mode symbols do lists of direct parent mode symbols.
671 This list is populated when reading the \".yas-parents\" files
672 found when traversing snippet directories with
673 `yas-load-directory'.
675 There might be additional parenting information stored in the
676 `derived-mode-parent' property of some mode symbols, but that is
679 (defvar yas--direct-keymaps (list)
680 "Keymap alist supporting direct snippet keybindings.
682 This variable is placed in `emulation-mode-map-alists'.
684 Its elements looks like (TABLE-NAME . KEYMAP). They're
685 instantiated on `yas-reload-all' but KEYMAP is added to only when
686 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
687 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
688 defined direct keybindings to the command
689 `yas-expand-from-keymap' which then which snippet to expand.")
691 (defun yas-direct-keymaps-reload ()
692 "Force reload the direct keybinding for active snippet tables."
694 (setq yas--direct-keymaps nil)
695 (maphash #'(lambda (name table)
696 (push (cons (intern (format "yas--direct-%s" name))
697 (yas--table-direct-keymap table))
698 yas--direct-keymaps))
701 (defun yas--modes-to-activate ()
702 "Compute list of mode symbols that are active for `yas-expand'
705 (setq dfs (lambda (mode &optional explored)
709 in (remove nil (cons (get mode
710 'derived-mode-parent)
711 (gethash mode yas--parents)))
713 unless (memq neighbour explored)
714 append (funcall dfs neighbour explored)))))
715 (remove-duplicates (append yas--extra-modes
716 (funcall dfs major-mode)))))
718 (defvar yas-minor-mode-hook nil
719 "Hook run when `yas-minor-mode' is turned on.")
722 (define-minor-mode yas-minor-mode
723 "Toggle YASnippet mode.
725 When YASnippet mode is enabled, `yas-expand', normally bound to
726 the TAB key, expands snippets of code depending on the major
729 With no argument, this command toggles the mode.
730 positive prefix argument turns on the mode.
731 Negative prefix argument turns off the mode.
734 \\{yas-minor-mode-map}"
736 ;; The indicator for the mode line.
739 (cond (yas-minor-mode
740 ;; Install the direct keymaps in `emulation-mode-map-alists'
741 ;; (we use `add-hook' even though it's not technically a hook,
742 ;; but it works). Then define variables named after modes to
743 ;; index `yas--direct-keymaps'.
745 ;; Also install the post-command-hook.
747 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
748 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
749 ;; Set the `yas--direct-%s' vars for direct keymap expansion
751 (dolist (mode (yas--modes-to-activate))
752 (let ((name (intern (format "yas--direct-%s" mode))))
753 (set-default name nil)
754 (set (make-local-variable name) t)))
757 (yas--load-pending-jits))
759 ;; Uninstall the direct keymaps and the post-command hook
761 (remove-hook 'post-command-hook 'yas--post-command-handler t)
762 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
764 (defun yas-activate-extra-mode (mode)
765 "Activates the snippets for the given `mode' in the buffer.
767 The function can be called in the hook of a minor mode to
768 activate snippets associated with that mode."
772 (maphash (lambda (k _)
773 (setq modes (cons (list k) modes)))
775 (setq symbol (completing-read
776 "Activate mode: " modes nil t))
778 (when (not (string= "" symbol))
781 (make-variable-buffer-local 'yas--extra-modes)
782 (add-to-list 'yas--extra-modes mode)
783 (yas--load-pending-jits)))
785 (defun yas-deactivate-extra-mode (mode)
786 "Deactivates the snippets for the given `mode' in the buffer."
790 "Deactivate mode: " (mapcar #'list yas--extra-modes) nil t))))
791 (setq yas--extra-modes
795 (defvar yas-dont-activate '(minibufferp)
796 "If non-nil don't let `yas-global-mode' affect some buffers.
798 If a function of zero arguments, then its result is used.
800 If a list of functions, then all functions must return nil to
801 activate yas for this buffer.
803 In Emacsen <= 23, this variable is buffer-local. Because
804 `yas-minor-mode-on' is called by `yas-global-mode' after
805 executing the buffer's major mode hook, setting this variable
806 there is an effective way to define exceptions to the \"global\"
807 activation behaviour.
809 In Emacsen > 23, only the global value is used. To define
810 per-mode exceptions to the \"global\" activation behaviour, call
811 `yas-minor-mode' with a negative argument directily in the major
813 (unless (> emacs-major-version 23)
815 (make-variable-buffer-local 'yas-dont-activate)))
818 (defun yas-minor-mode-on ()
819 "Turn on YASnippet minor mode.
821 Honour `yas-dont-activate', which see."
823 ;; Check `yas-dont-activate'
824 (unless (cond ((functionp yas-dont-activate)
825 (funcall yas-dont-activate))
826 ((consp yas-dont-activate)
827 (some #'funcall yas-dont-activate))
832 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
836 (defun yas--global-mode-reload-with-jit-maybe ()
837 "Run `yas-reload-all' when `yas-global-mode' is on."
838 (when yas-global-mode (yas-reload-all)))
840 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
845 (defvar yas--font-lock-keywords
846 (append '(("^#.*$" . font-lock-comment-face))
847 lisp-font-lock-keywords-2
849 (0 font-lock-keyword-face)
850 (1 font-lock-string-face t))
852 (0 font-lock-keyword-face)
853 (1 font-lock-warning-face t))
854 ("${" . font-lock-keyword-face)
855 ("$[0-9]+?" . font-lock-preprocessor-face)
856 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
858 (0 font-lock-keyword-face)))))
860 (defvar snippet-mode-map
861 (let ((map (make-sparse-keymap)))
862 (easy-menu-define nil
864 "Menu used when snippet-mode is active."
866 (mapcar #'(lambda (ent)
868 (define-key map (third ent) (second ent)))
869 (vector (first ent) (second ent) t))
870 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
871 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
872 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
874 "The keymap used when `snippet-mode' is active.")
877 (define-derived-mode snippet-mode text-mode "Snippet"
878 "A mode for editing yasnippets"
879 (setq font-lock-defaults '(yas--font-lock-keywords))
880 (set (make-local-variable 'require-final-newline) nil)
881 (set (make-local-variable 'comment-start) "#")
882 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
886 ;;; Internal structs for template management
888 (defstruct (yas--template (:constructor yas--make-blank-template))
889 "A template for a snippet."
899 group ;; as dictated by the #group: directive or .yas-make-groups
900 perm-group ;; as dictated by `yas-define-menu'
904 (defun yas--populate-template (template &rest args)
905 "Helper function to populate TEMPLATE with properties."
908 (position (intern (substring (symbol-name (car args)) 1))
909 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
911 (setq args (cddr args)))
914 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
915 "A table to store snippets for a particular mode.
917 Has the following fields:
921 A symbol name normally corresponding to a major mode, but can
922 also be a pseudo major-mode to be used in
923 `yas-activate-extra-mode', for example.
927 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
928 a string or a vector, where the former is the snippet's trigger
929 and the latter means it's a direct keybinding. NAMEHASH is yet
930 another hash of (NAME . TEMPLATE) where NAME is the snippet's
931 name and TEMPLATE is a `yas--template' object.
933 `yas--table-direct-keymap'
935 A keymap for the snippets in this table that have direct
936 keybindings. This is kept in sync with the keyhash, i.e., all
937 the elements of the keyhash that are vectors appear here as
938 bindings to `yas-expand-from-keymap'.
940 `yas--table-uuidhash'
942 A hash table mapping snippets uuid's to the same `yas--template'
943 objects. A snippet uuid defaults to the snippet's name."
945 (hash (make-hash-table :test 'equal))
946 (uuidhash (make-hash-table :test 'equal))
948 (direct-keymap (make-sparse-keymap)))
950 (defun yas--get-template-by-uuid (mode uuid)
951 "Find the snippet template in MODE by its UUID."
952 (let* ((table (gethash mode yas--tables mode)))
954 (gethash uuid (yas--table-uuidhash table)))))
956 ;; Apropos storing/updating in TABLE, this works in two steps:
958 ;; 1. `yas--remove-template-by-uuid' removes any
959 ;; keyhash-namehash-template mappings from TABLE, grabbing the
960 ;; snippet by its uuid. Also removes mappings from TABLE's
961 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
962 ;; of potentially stale menu bindings right?.)
964 ;; 2. `yas--add-template' adds this all over again.
966 ;; Create a new or add to an existing keyhash-namehash mapping.
968 ;; For reference on understanding this, consider three snippet
971 ;; A: # name: The Foo
973 ;; # binding: C-c M-l
975 ;; B: # name: Mrs Foo
978 ;; C: # name: The Bar
979 ;; # binding: C-c M-l
984 ;; keyhash namehashes(3) yas--template structs(4)
985 ;; -----------------------------------------------------
988 ;; "foo" ---> "The Foo" ---> [yas--template A] |
989 ;; "Mrs Foo" ---> [yas--template B] |
991 ;; [C-c M-l] ---> "The Foo" -------------------------/
992 ;; "The Bar" ---> [yas--template C]
994 ;; "baz" ---> "Baz" ---> [yas--template D]
996 ;; Additionally, since uuid defaults to the name, we have a
997 ;; `yas--table-uuidhash' for TABLE
999 ;; uuidhash yas--template structs
1000 ;; -------------------------------
1001 ;; "The Foo" ---> [yas--template A]
1002 ;; "Mrs Foo" ---> [yas--template B]
1003 ;; "The Bar" ---> [yas--template C]
1004 ;; "Baz" ---> [yas--template D]
1006 ;; FIXME: the more I look at this data-structure the more I think I'm
1007 ;; stupid. There has to be an easier way (but beware lots of code
1008 ;; depends on this).
1010 (defun yas--remove-template-by-uuid (table uuid)
1011 "Remove from TABLE a template identified by UUID."
1012 (let ((template (gethash uuid (yas--table-uuidhash table))))
1014 (let* ((name (yas--template-name template))
1016 ;; Remove the name from each of the targeted namehashes
1018 (maphash #'(lambda (k v)
1019 (let ((template (gethash name v)))
1021 (eq uuid (yas--template-uuid template)))
1023 (when (zerop (hash-table-count v))
1024 (push k empty-keys)))))
1025 (yas--table-hash table))
1026 ;; Remove the namehash themselves if they've become empty
1028 (dolist (key empty-keys)
1030 (define-key (yas--table-direct-keymap table) key nil))
1031 (remhash key (yas--table-hash table)))
1033 ;; Finally, remove the uuid from the uuidhash
1035 (remhash uuid (yas--table-uuidhash table))))))
1037 (defun yas--add-template (table template)
1038 "Store in TABLE the snippet template TEMPLATE.
1040 KEY can be a string (trigger key) of a vector (direct
1042 (let ((name (yas--template-name template))
1043 (key (yas--template-key template))
1044 (keybinding (yas--template-keybinding template))
1045 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1046 (dolist (k (remove nil (list key keybinding)))
1050 (yas--table-hash table))
1052 (make-hash-table :test 'equal)
1053 (yas--table-hash table))))
1055 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1057 ;; Update TABLE's `yas--table-uuidhash'
1058 (puthash (yas--template-uuid template)
1060 (yas--table-uuidhash table))))
1062 (defun yas--update-template (table template)
1063 "Add or update TEMPLATE in TABLE.
1065 Also takes care of adding and updating to the associated menu."
1066 ;; Remove from table by uuid
1068 (yas--remove-template-by-uuid table (yas--template-uuid template))
1069 ;; Add to table again
1071 (yas--add-template table template)
1072 ;; Take care of the menu
1075 (yas--update-template-menu table template)))
1077 (defun yas--update-template-menu (table template)
1078 "Update every menu-related for TEMPLATE."
1079 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1080 (key (yas--template-key template))
1081 (keybinding (yas--template-keybinding template)))
1082 ;; The snippet might have changed name or keys, so update
1083 ;; user-visible strings
1085 (unless (eq (cdr menu-binding-pair) :none)
1086 ;; the menu item name
1088 (setf (cadar menu-binding-pair) (yas--template-name template))
1089 ;; the :keys information (also visible to the user)
1090 (setf (getf (cdr (car menu-binding-pair)) :keys)
1091 (or (and keybinding (key-description keybinding))
1092 (and key (concat key yas-trigger-symbol))))))
1093 (unless (yas--template-menu-managed-by-yas-define-menu template)
1095 (yas--menu-keymap-get-create (yas--table-mode table)
1096 (mapcar #'yas--table-mode
1097 (yas--table-parents table))))
1098 (group (yas--template-group template)))
1099 ;; Remove from menu keymap
1101 (assert menu-keymap)
1102 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1104 ;; Add necessary subgroups as necessary.
1106 (dolist (subgroup group)
1107 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1108 (unless (and subgroup-keymap
1109 (keymapp subgroup-keymap))
1110 (setq subgroup-keymap (make-sparse-keymap))
1111 (define-key menu-keymap (vector (make-symbol subgroup))
1112 `(menu-item ,subgroup ,subgroup-keymap)))
1113 (setq menu-keymap subgroup-keymap)))
1115 ;; Add this entry to the keymap
1117 (define-key menu-keymap
1118 (vector (make-symbol (yas--template-uuid template)))
1119 (car (yas--template-menu-binding-pair template))))))
1121 (defun yas--namehash-templates-alist (namehash)
1122 "Return NAMEHASH as an alist."
1124 (maphash #'(lambda (k v)
1125 (push (cons k v) alist))
1129 (defun yas--fetch (table key)
1130 "Fetch templates in TABLE by KEY.
1132 Return a list of cons (NAME . TEMPLATE) where NAME is a
1133 string and TEMPLATE is a `yas--template' structure."
1134 (let* ((keyhash (yas--table-hash table))
1135 (namehash (and keyhash (gethash key keyhash))))
1137 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1140 ;;; Filtering/condition logic
1142 (defun yas--eval-condition (condition)
1149 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1153 (defun yas--filter-templates-by-condition (templates)
1154 "Filter the templates using the applicable condition.
1156 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1157 string and TEMPLATE is a `yas--template' structure.
1159 This function implements the rules described in
1160 `yas-buffer-local-condition'. See that variables documentation."
1161 (let ((requirement (yas--require-template-specific-condition-p)))
1162 (if (eq requirement 'always)
1164 (remove-if-not #'(lambda (pair)
1165 (yas--template-can-expand-p
1166 (yas--template-condition (cdr pair)) requirement))
1169 (defun yas--require-template-specific-condition-p ()
1170 "Decide if this buffer requests/requires snippet-specific
1171 conditions to filter out potential expansions."
1172 (if (eq 'always yas-buffer-local-condition)
1174 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1175 (yas--eval-condition yas-buffer-local-condition))
1176 yas-buffer-local-condition)))
1177 (when local-condition
1178 (if (eq local-condition t)
1180 (and (consp local-condition)
1181 (eq 'require-snippet-condition (car local-condition))
1182 (symbolp (cdr local-condition))
1183 (cdr local-condition)))))))
1185 (defun yas--template-can-expand-p (condition requirement)
1186 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1187 (let* ((result (or (null condition)
1188 (yas--eval-condition condition))))
1189 (cond ((eq requirement t)
1192 (eq requirement result)))))
1194 (defun yas--table-templates (table)
1197 (maphash #'(lambda (_key namehash)
1198 (maphash #'(lambda (name template)
1199 (push (cons name template) acc))
1201 (yas--table-hash table))
1202 (yas--filter-templates-by-condition acc))))
1204 (defun yas--current-key ()
1205 "Get the key under current position.
1206 A key is used to find the template of a snippet in the current snippet-table."
1207 (let ((start (point))
1209 (syntaxes yas-key-syntaxes)
1213 (while (and (not done) syntaxes)
1214 (setq syntax (car syntaxes))
1215 (setq syntaxes (cdr syntaxes))
1217 (skip-syntax-backward syntax)
1218 (setq start (point)))
1220 (mapcan #'(lambda (table)
1221 (yas--fetch table (buffer-substring-no-properties start end)))
1222 (yas--get-snippet-tables)))
1231 (defun yas--table-all-keys (table)
1232 "Get trigger keys of all active snippets in TABLE."
1234 (maphash #'(lambda (key namehash)
1235 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1237 (yas--table-hash table))
1240 (defun yas--table-mode (table)
1241 (intern (yas--table-name table)))
1244 ;;; Internal functions and macros:
1246 (defun yas--real-mode? (mode)
1247 "Try to find out if MODE is a real mode.
1249 The MODE bound to a function (like `c-mode') is considered real
1250 mode. Other well known mode like `ruby-mode' which is not part of
1251 Emacs might not bound to a function until it is loaded. So
1252 yasnippet keeps a list of modes like this to help the judgment."
1254 (find mode yas--known-modes)))
1256 (defun yas--eval-lisp (form)
1257 "Evaluate FORM and convert the result to string."
1258 (let ((retval (catch 'yas--exception
1264 (let ((result (eval form)))
1266 (format "%s" result))))))
1267 (error (if yas-good-grace
1268 (yas--format "elisp error! %s" (error-message-string err))
1269 (error (yas--format "elisp error: %s"
1270 (error-message-string err)))))))))
1271 (when (and (consp retval)
1272 (eq 'yas--exception (car retval)))
1273 (error (cdr retval)))
1276 (defun yas--eval-lisp-no-saves (form)
1279 (error (if yas-good-grace
1280 (yas--format "elisp error! %s" (error-message-string err))
1281 (error (yas--format "elisp error: %s"
1282 (error-message-string err)))))))
1284 (defun yas--read-lisp (string &optional nil-on-error)
1285 "Read STRING as a elisp expression and return it.
1287 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1288 return an expression that when evaluated will issue an error."
1291 (error (and (not nil-on-error)
1292 `(error (error-message-string ,err))))))
1294 (defun yas--read-keybinding (keybinding)
1295 "Read KEYBINDING as a snippet keybinding, return a vector."
1296 (when (and keybinding
1297 (not (string-match "keybinding" keybinding)))
1299 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1301 (read-kbd-macro keybinding 'need-vector))))
1304 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1305 keybinding (error-message-string err))
1308 (defun yas--table-get-create (mode)
1309 "Get or create the snippet table corresponding to MODE."
1310 (let ((table (gethash mode
1313 (setq table (yas--make-snippet-table (symbol-name mode)))
1314 (puthash mode table yas--tables)
1315 (push (cons (intern (format "yas--direct-%s" mode))
1316 (yas--table-direct-keymap table))
1317 yas--direct-keymaps))
1320 (defun yas--get-snippet-tables ()
1321 "Get snippet tables for current buffer.
1323 Return a list of `yas--table' objects. The list of modes to
1324 consider is returned by `yas--modes-to-activate'"
1326 (mapcar #'(lambda (name)
1327 (gethash name yas--tables))
1328 (yas--modes-to-activate))))
1330 (defun yas--menu-keymap-get-create (mode &optional parents)
1331 "Get or create the menu keymap for MODE and its PARENTS.
1333 This may very well create a plethora of menu keymaps and arrange
1334 them all in `yas--menu-table'"
1335 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1336 (puthash mode (make-sparse-keymap) yas--menu-table))))
1337 (mapc #'yas--menu-keymap-get-create parents)
1338 (define-key yas--minor-mode-menu (vector mode)
1339 `(menu-item ,(symbol-name mode) ,menu-keymap
1340 :visible (yas--show-menu-p ',mode)))
1344 (defmacro yas--called-interactively-p (&optional kind)
1345 "A backward-compatible version of `called-interactively-p'.
1347 Optional KIND is as documented at `called-interactively-p'
1348 in GNU Emacs 24.1 or higher."
1349 (if (string< emacs-version "24.1")
1350 '(called-interactively-p)
1351 `(called-interactively-p ,kind)))
1354 ;;; Template-related and snippet loading functions
1356 (defun yas--parse-template (&optional file)
1357 "Parse the template in the current buffer.
1359 Optional FILE is the absolute file name of the file being
1362 Optional GROUP is the group where the template is to go,
1363 otherwise we attempt to calculate it from FILE.
1365 Return a snippet-definition, i.e. a list
1367 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1369 If the buffer contains a line of \"# --\" then the contents above
1370 this line are ignored. Directives can set most of these with the syntax:
1372 # directive-name : directive-value
1374 Here's a list of currently recognized directives:
1385 (goto-char (point-min))
1386 (let* ((type 'snippet)
1388 (file-name-nondirectory file)))
1394 (yas--calculate-group file)))
1398 (if (re-search-forward "^# --\n" nil t)
1399 (progn (setq template
1400 (buffer-substring-no-properties (point)
1402 (setq bound (point))
1403 (goto-char (point-min))
1404 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1405 (when (string= "uuid" (match-string-no-properties 1))
1406 (setq uuid (match-string-no-properties 2)))
1407 (when (string= "type" (match-string-no-properties 1))
1408 (setq type (if (string= "command" (match-string-no-properties 2))
1411 (when (string= "key" (match-string-no-properties 1))
1412 (setq key (match-string-no-properties 2)))
1413 (when (string= "name" (match-string-no-properties 1))
1414 (setq name (match-string-no-properties 2)))
1415 (when (string= "condition" (match-string-no-properties 1))
1416 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1417 (when (string= "group" (match-string-no-properties 1))
1418 (setq group (match-string-no-properties 2)))
1419 (when (string= "expand-env" (match-string-no-properties 1))
1420 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1422 (when (string= "binding" (match-string-no-properties 1))
1423 (setq binding (match-string-no-properties 2)))))
1425 (buffer-substring-no-properties (point-min) (point-max))))
1426 (unless (or key binding)
1427 (setq key (and file (file-name-nondirectory file))))
1428 (when (eq type 'command)
1429 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1431 (setq group (split-string group "\\.")))
1432 (list key template name condition group expand-env file binding uuid)))
1434 (defun yas--calculate-group (file)
1435 "Calculate the group for snippet file path FILE."
1436 (let* ((dominating-dir (locate-dominating-file file
1437 ".yas-make-groups"))
1438 (extra-path (and dominating-dir
1439 (replace-regexp-in-string (concat "^"
1440 (expand-file-name dominating-dir))
1442 (expand-file-name file))))
1443 (extra-dir (and extra-path
1444 (file-name-directory extra-path)))
1445 (group (and extra-dir
1446 (replace-regexp-in-string "/"
1448 (directory-file-name extra-dir)))))
1451 (defun yas--subdirs (directory &optional filep)
1452 "Return subdirs or files of DIRECTORY according to FILEP."
1453 (remove-if (lambda (file)
1454 (or (string-match "^\\."
1455 (file-name-nondirectory file))
1456 (string-match "^#.*#$"
1457 (file-name-nondirectory file))
1459 (file-name-nondirectory file))
1461 (file-directory-p file)
1462 (not (file-directory-p file)))))
1463 (directory-files directory t)))
1465 (defun yas--make-menu-binding (template)
1466 (let ((mode (yas--table-mode (yas--template-table template))))
1467 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1469 (defun yas--expand-or-visit-from-menu (mode uuid)
1470 (let* ((table (yas--table-get-create mode))
1471 (yas--current-template (and table
1472 (gethash uuid (yas--table-uuidhash table)))))
1473 (when yas--current-template
1474 (if yas-visit-from-menu
1475 (yas--visit-snippet-file-1 yas--current-template)
1476 (let ((where (if (region-active-p)
1477 (cons (region-beginning) (region-end))
1478 (cons (point) (point)))))
1479 (yas-expand-snippet (yas--template-content yas--current-template)
1482 (yas--template-expand-env yas--current-template)))))))
1484 (defun yas--key-from-desc (text)
1485 "Return a yasnippet key from a description string TEXT."
1486 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1489 ;;; Popping up for keys and templates
1491 (defvar yas--x-pretty-prompt-templates nil
1492 "If non-nil, attempt to prompt for templates like TextMate.")
1495 (defun yas--prompt-for-template (templates &optional prompt)
1496 "Interactively choose a template from the list TEMPLATES.
1498 TEMPLATES is a list of `yas--template'.
1500 Optional PROMPT sets the prompt to use."
1503 (sort templates #'(lambda (t1 t2)
1504 (< (length (yas--template-name t1))
1505 (length (yas--template-name t2))))))
1506 (if yas--x-pretty-prompt-templates
1507 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1508 (some #'(lambda (fn)
1509 (funcall fn (or prompt "Choose a snippet: ")
1511 #'yas--template-name))
1512 yas-prompt-functions))))
1514 (defun yas--prompt-for-keys (keys &optional prompt)
1515 "Interactively choose a template key from the list KEYS.
1517 Optional PROMPT sets the prompt to use."
1519 (some #'(lambda (fn)
1520 (funcall fn (or prompt "Choose a snippet key: ") keys))
1521 yas-prompt-functions)))
1523 (defun yas--prompt-for-table (tables &optional prompt)
1524 "Interactively choose a table from the list TABLES.
1526 Optional PROMPT sets the prompt to use."
1528 (some #'(lambda (fn)
1529 (funcall fn (or prompt "Choose a snippet table: ")
1532 yas-prompt-functions)))
1534 (defun yas-x-prompt (prompt choices &optional display-fn)
1535 "Display choices in a x-window prompt."
1536 ;; FIXME: HACK: if we notice that one of the objects in choices is
1537 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1539 ;; This would be better implemented by passing CHOICES as a
1540 ;; structured tree rather than a list. Modifications would go as far
1541 ;; up as `yas--all-templates' I think.
1543 (when (and window-system choices)
1545 (let (menu d) ;; d for display
1547 (setq d (or (and display-fn (funcall display-fn c))
1550 (push (cons (concat " " d) c) menu))
1552 (push (car d) menu))))
1553 (setq menu (list prompt (push "title" menu)))
1554 (x-popup-menu (if (fboundp 'posn-at-point)
1555 (let ((x-y (posn-x-y (posn-at-point (point)))))
1556 (list (list (+ (car x-y) 10)
1564 (defun yas--x-pretty-prompt-templates (prompt templates)
1565 "Display TEMPLATES, grouping neatly by table name."
1566 (let ((organized (make-hash-table :test #'equal))
1570 (dolist (tl templates)
1571 (puthash (yas--template-table tl)
1573 (gethash (yas--template-table tl) organized))
1575 (setq more-than-one-table (> (hash-table-count organized) 1))
1576 (setq prefix (if more-than-one-table
1578 (if more-than-one-table
1579 (maphash #'(lambda (table templates)
1580 (push (yas--table-name table) menu)
1581 (dolist (tl templates)
1582 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1583 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1585 (setq menu (nreverse menu))
1586 (or (x-popup-menu (if (fboundp 'posn-at-point)
1587 (let ((x-y (posn-x-y (posn-at-point (point)))))
1588 (list (list (+ (car x-y) 10)
1592 (list prompt (push "title" menu)))
1595 (defun yas-ido-prompt (prompt choices &optional display-fn)
1596 (when (and (fboundp 'ido-completing-read)
1597 (or (>= emacs-major-version 24)
1599 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1601 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1602 (when (fboundp 'dropdown-list)
1603 (let (formatted-choices
1607 (dolist (choice choices)
1608 (setq d (or (and display-fn (funcall display-fn choice))
1611 (push d formatted-choices)
1612 (push choice filtered-choices)))
1614 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1616 (nth n filtered-choices)
1619 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1620 (let (formatted-choices
1624 (completion-fn (or completion-fn
1625 #'completing-read)))
1626 (dolist (choice choices)
1627 (setq d (or (and display-fn (funcall display-fn choice))
1630 (push d formatted-choices)
1631 (push choice filtered-choices)))
1632 (setq chosen (and formatted-choices
1633 (funcall completion-fn prompt
1639 (let ((position (or (and chosen
1640 (position chosen formatted-choices :test #'string=))
1642 (nth position filtered-choices))))
1644 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1648 ;;; Defining snippets
1649 ;; This consists of creating and registering `yas--template' objects in the
1653 (defvar yas--creating-compiled-snippets nil)
1655 (defun yas--define-snippets-1 (snippet snippet-table)
1656 "Helper for `yas-define-snippets'."
1657 ;; X) Calculate some more defaults on the values returned by
1658 ;; `yas--parse-template'.
1660 (let* ((file (seventh snippet))
1662 (name (or (third snippet)
1664 (file-name-directory file))))
1665 (condition (fourth snippet))
1666 (group (fifth snippet))
1667 (keybinding (yas--read-keybinding (eighth snippet)))
1668 (uuid (or (ninth snippet)
1670 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1671 (yas--make-blank-template))))
1672 ;; X) populate the template object
1674 (yas--populate-template template
1675 :table snippet-table
1677 :content (second snippet)
1680 :condition condition
1681 :expand-env (sixth snippet)
1682 :file (seventh snippet)
1683 :keybinding keybinding
1685 ;; X) Update this template in the appropriate table. This step
1686 ;; also will take care of adding the key indicators in the
1687 ;; templates menu entry, if any
1689 (yas--update-template snippet-table template)
1690 ;; X) Return the template
1695 (defun yas-define-snippets (mode snippets)
1696 "Define SNIPPETS for MODE.
1698 SNIPPETS is a list of snippet definitions, each taking the
1701 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1703 Within these, only KEY and TEMPLATE are actually mandatory.
1705 TEMPLATE might be a Lisp form or a string, depending on whether
1706 this is a snippet or a snippet-command.
1708 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1709 been `yas--read-lisp'-ed and will eventually be
1710 `yas--eval-lisp'-ed.
1712 The remaining elements are strings.
1714 FILE is probably of very little use if you're programatically
1717 UUID is the snippets \"unique-id\". Loading a second snippet file
1718 with the same uuid replaced the previous snippet.
1720 You can use `yas--parse-template' to return such lists based on
1721 the current buffers contents."
1722 (if yas--creating-compiled-snippets
1724 (insert ";;; Snippet definitions:\n;;;\n")
1725 (let ((literal-snippets (list))
1727 (dolist (snippet snippets)
1728 (let ((key (nth 0 snippet))
1729 (template-content (nth 1 snippet))
1730 (name (nth 2 snippet))
1731 (condition (nth 3 snippet))
1732 (group (nth 4 snippet))
1733 (expand-env (nth 5 snippet))
1734 (file nil) ;; omit on purpose
1735 (binding (nth 7 snippet))
1736 (uuid (nth 8 snippet)))
1747 (insert (pp-to-string
1748 `(yas-define-snippets ',mode ',literal-snippets)))
1751 (let ((snippet-table (yas--table-get-create mode))
1753 (dolist (snippet snippets)
1754 (setq template (yas--define-snippets-1 snippet
1759 ;;; Loading snippets from files
1761 (defun yas--load-yas-setup-file (file)
1762 (if (not yas--creating-compiled-snippets)
1764 (load file 'noerror)
1765 (let ((elfile (concat file ".el")))
1766 (when (file-exists-p elfile)
1767 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1768 (insert-file-contents elfile)
1769 (goto-char (point-max))))))
1771 (defun yas--define-parents (mode parents)
1772 "Add PARENTS to the list of MODE's parents."
1773 (puthash mode (remove-duplicates
1775 (gethash mode yas--parents)))
1778 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1779 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1781 Below TOP-LEVEL-DIR each directory should be a mode name.
1783 Optional USE-JIT use jit-loading of snippets."
1784 (interactive "DSelect the root directory: ni\np")
1785 (unless yas-snippet-dirs
1786 (setq yas-snippet-dirs top-level-dir))
1787 (dolist (dir (yas--subdirs top-level-dir))
1788 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1789 (concat dir "/dummy")))
1790 (mode-sym (car major-mode-and-parents))
1791 (parents (cdr major-mode-and-parents)))
1792 ;; Attention: The parents and the menus are already defined
1793 ;; here, even if the snippets are later jit-loaded.
1795 ;; * We need to know the parents at this point since entering a
1796 ;; given mode should jit load for its parents
1797 ;; immediately. This could be reviewed, the parents could be
1798 ;; discovered just-in-time-as well
1800 ;; * We need to create the menus here to support the `full'
1801 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1803 (yas--define-parents mode-sym parents)
1804 (yas--menu-keymap-get-create mode-sym)
1805 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1806 (yas--load-directory-1 ',dir ',mode-sym))))
1808 (not (some #'(lambda (buffer)
1809 (with-current-buffer buffer
1810 ;; FIXME: Shouldn't this use derived-mode-p?
1811 (when (eq major-mode mode-sym)
1812 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1815 (yas--schedule-jit mode-sym fun)
1818 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1820 (defun yas--load-directory-1 (directory mode-sym)
1821 "Recursively load snippet templates from DIRECTORY."
1822 (if yas--creating-compiled-snippets
1823 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1825 (with-temp-file output-file
1826 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1828 (yas--load-directory-2 directory mode-sym)
1829 (insert (format ";;; Do not edit! File generated at %s\n"
1830 (current-time-string)))))
1832 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1833 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1834 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1835 (yas--message 2 "Loading snippet files from %s" directory)
1836 (yas--load-directory-2 directory mode-sym)))))
1838 (defun yas--load-directory-2 (directory mode-sym)
1839 ;; Load .yas-setup.el files wherever we find them
1841 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1842 (let* ((default-directory directory)
1844 ;; load the snippet files
1847 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1848 (when (file-readable-p file)
1849 (insert-file-contents file nil nil nil t)
1850 (push (yas--parse-template file)
1853 (yas-define-snippets mode-sym
1855 ;; now recurse to a lower level
1857 (dolist (subdir (yas--subdirs directory))
1858 (yas--load-directory-2 subdir
1861 (defun yas--load-snippet-dirs (&optional nojit)
1862 "Reload the directories listed in `yas-snippet-dirs' or
1863 prompt the user to select one."
1865 (if yas-snippet-dirs
1866 (dolist (directory (reverse (yas-snippet-dirs)))
1867 (cond ((file-directory-p directory)
1868 (yas-load-directory directory (not nojit))
1870 (yas--message 3 "Loaded %s" directory)
1871 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1873 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1874 (call-interactively 'yas-load-directory))
1877 (defun yas-reload-all (&optional interactive)
1878 "Reload all snippets and rebuild the YASnippet menu.
1880 When called interactively force immediate reload of all known
1881 snippets under `yas-snippet-dirs', otherwise use just-in-time
1886 (snippet-editing-buffers
1887 (remove-if-not #'(lambda (buffer)
1888 (with-current-buffer buffer yas--editing-template))
1890 ;; Warn if there are buffers visiting snippets, since reloading will break
1891 ;; any on-line editing of those buffers.
1893 (when snippet-editing-buffers
1895 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1896 (mapc #'kill-buffer snippet-editing-buffers)
1897 (yas--message 1 "Aborted reload...")
1899 ;; in a non-interactive use, at least set
1900 ;; `yas--editing-template' to nil, make it guess it next time around
1901 (mapc #'(lambda (buffer)
1902 (with-current-buffer buffer
1903 (kill-local-variable 'yas--editing-template)))
1906 ;; Empty all snippet tables and parenting info
1908 (setq yas--tables (make-hash-table))
1909 (setq yas--parents (make-hash-table))
1911 ;; Before killing `yas--menu-table' use its keys to cleanup the
1912 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1913 ;; up `yas-minor-mode-map', which points to it)
1915 (maphash #'(lambda (menu-symbol _keymap)
1916 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1918 ;; Now empty `yas--menu-table' as well
1919 (setq yas--menu-table (make-hash-table))
1921 ;; Cancel all pending 'yas--scheduled-jit-loads'
1923 (setq yas--scheduled-jit-loads (make-hash-table))
1925 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1926 ;; the user to select one.
1928 (setq errors (yas--load-snippet-dirs interactive))
1929 ;; Reload the direct keybindings
1931 (yas-direct-keymaps-reload)
1933 (yas--message 3 "Reloaded everything%s...%s."
1934 (if interactive "" " (snippets will load just-in-time)")
1935 (if errors " (some errors, check *Messages*)" "")))))
1937 (defun yas--load-pending-jits ()
1938 (dolist (mode (yas--modes-to-activate))
1939 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1940 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1942 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1944 (remhash mode yas--scheduled-jit-loads))))
1946 ;; (when (<= emacs-major-version 22)
1947 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1949 (defun yas--quote-string (string)
1950 "Escape and quote STRING.
1951 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1953 (replace-regexp-in-string "[\\\"]"
1959 ;;; Snippet compilation function
1961 (defun yas--initialize ()
1962 "For backward compatibility, enable `yas-minor-mode' globally."
1963 (yas-global-mode 1))
1965 (defun yas-compile-directory (top-level-dir)
1966 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1968 This works by stubbing a few functions, then calling
1969 `yas-load-directory'."
1970 (interactive "DTop level snippet directory?")
1971 (let ((yas--creating-compiled-snippets t))
1972 (yas-load-directory top-level-dir nil)))
1974 (defun yas-recompile-all ()
1975 "Compile every dir in `yas-snippet-dirs'."
1977 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1983 (defvar yas--scheduled-jit-loads (make-hash-table)
1984 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1986 (defun yas--schedule-jit (mode fun)
1987 (push fun (gethash mode yas--scheduled-jit-loads)))
1991 ;;; Some user level functions
1995 (message (concat "yasnippet (version "
1997 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2000 ;;; Apropos snippet menu:
2002 ;; The snippet menu keymaps are store by mode in hash table called
2003 ;; `yas--menu-table'. They are linked to the main menu in
2004 ;; `yas--menu-keymap-get-create' and are initially created empty,
2005 ;; reflecting the table hierarchy.
2007 ;; They can be populated in two mutually exclusive ways: (1) by
2008 ;; reading `yas--template-group', which in turn is populated by the "#
2009 ;; group:" directives of the snippets or the ".yas-make-groups" file
2010 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2011 ;; menu structure based on snippets uuids.
2013 ;; Both situations are handled in `yas--update-template-menu', which
2014 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2015 ;; that can tell between the two situations.
2019 ;; * if `yas-define-menu' is used it must run before
2020 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2021 ;; duplicate entries. The `yas--template' objects are created in
2022 ;; `yas-define-menu', holding nothing but the menu entry,
2023 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2024 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2025 ;; part is then stored in the menu keymap itself which make the item
2026 ;; appear to the user. These limitations could probably be revised.
2028 ;; * The `yas--template-perm-group' slot is only used in
2029 ;; `yas-describe-tables'.
2031 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2032 "Get TEMPLATE's menu binding or assign it a new one.
2034 TYPE may be `:stay', signaling this menu binding should be
2035 static in the menu."
2036 (or (yas--template-menu-binding-pair template)
2037 (let (;; (key (yas--template-key template))
2038 ;; (keybinding (yas--template-keybinding template))
2040 (setf (yas--template-menu-binding-pair template)
2041 (cons `(menu-item ,(or (yas--template-name template)
2042 (yas--template-uuid template))
2043 ,(yas--make-menu-binding template)
2046 (defun yas--template-menu-managed-by-yas-define-menu (template)
2047 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2048 (cdr (yas--template-menu-binding-pair template)))
2051 (defun yas--show-menu-p (mode)
2052 (cond ((eq yas-use-menu 'abbreviate)
2054 (mapcar #'(lambda (table)
2055 (yas--table-mode table))
2056 (yas--get-snippet-tables))))
2057 ((eq yas-use-menu 'full)
2059 ((eq yas-use-menu t)
2062 (defun yas--delete-from-keymap (keymap uuid)
2063 "Recursively delete items with UUID from KEYMAP and its submenus."
2065 ;; XXX: This used to skip any submenus named \"parent mode\"
2067 ;; First of all, recursively enter submenus, i.e. the tree is
2068 ;; searched depth first so that stale submenus can be found in the
2071 (mapc #'(lambda (item)
2072 (when (and (listp (cdr item))
2073 (keymapp (third (cdr item))))
2074 (yas--delete-from-keymap (third (cdr item)) uuid)))
2076 ;; Set the uuid entry to nil
2078 (define-key keymap (vector (make-symbol uuid)) nil)
2079 ;; Destructively modify keymap
2081 (setcdr keymap (delete-if #'(lambda (item)
2082 (or (null (cdr item))
2083 (and (keymapp (third (cdr item)))
2084 (null (cdr (third (cdr item)))))))
2087 (defun yas-define-menu (mode menu &optional omit-items)
2088 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2090 MENU is a list, its elements can be:
2092 - (yas-item UUID) : Creates an entry the snippet identified with
2093 UUID. The menu entry for a snippet thus identified is
2094 permanent, i.e. it will never move (be reordered) in the menu.
2096 - (yas-separator) : Creates a separator
2098 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2099 SUBMENU has the same form as MENU. NAME is also added to the
2100 list of groups of the snippets defined thereafter.
2102 OMIT-ITEMS is a list of snippet uuid's that will always be
2103 omitted from MODE's menu, even if they're manually loaded.
2105 This function does nothing if `yas-use-menu' is nil."
2107 (let* ((table (yas--table-get-create mode))
2108 (hash (yas--table-uuidhash table)))
2109 (yas--define-menu-1 table
2110 (yas--menu-keymap-get-create mode)
2113 (dolist (uuid omit-items)
2114 (let ((template (or (gethash uuid hash)
2115 (yas--populate-template (puthash uuid
2116 (yas--make-blank-template)
2120 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2122 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2123 "Helper for `yas-define-menu'."
2124 (dolist (e (reverse menu))
2125 (cond ((eq (first e) 'yas-item)
2126 (let ((template (or (gethash (second e) uuidhash)
2127 (yas--populate-template (puthash (second e)
2128 (yas--make-blank-template)
2131 :perm-group group-list
2132 :uuid (second e)))))
2133 (define-key menu-keymap (vector (gensym))
2134 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2135 ((eq (first e) 'yas-submenu)
2136 (let ((subkeymap (make-sparse-keymap)))
2137 (define-key menu-keymap (vector (gensym))
2138 `(menu-item ,(second e) ,subkeymap))
2139 (yas--define-menu-1 table
2143 (append group-list (list (second e))))))
2144 ((eq (first e) 'yas-separator)
2145 (define-key menu-keymap (vector (gensym))
2146 '(menu-item "----")))
2148 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2150 (defun yas--define (mode key template &optional name condition group)
2151 "Define a snippet. Expanding KEY into TEMPLATE.
2153 NAME is a description to this template. Also update the menu if
2154 `yas-use-menu' is t. CONDITION is the condition attached to
2155 this snippet. If you attach a condition to a snippet, then it
2156 will only be expanded when the condition evaluated to non-nil."
2157 (yas-define-snippets mode
2158 (list (list key template name condition group))))
2160 (defun yas-hippie-try-expand (first-time?)
2161 "Integrate with hippie expand.
2163 Just put this function in `hippie-expand-try-functions-list'."
2164 (when yas-minor-mode
2165 (if (not first-time?)
2166 (let ((yas-fallback-behavior 'return-nil))
2172 ;;; Apropos condition-cache:
2177 (defvar yas--condition-cache-timestamp nil)
2178 (defmacro yas-define-condition-cache (func doc &rest body)
2179 "Define a function FUNC with doc DOC and body BODY.
2180 BODY is executed at most once every snippet expansion attempt, to check
2181 expansion conditions.
2183 It doesn't make any sense to call FUNC programatically."
2184 `(defun ,func () ,(if (and doc
2187 "\n\nFor use in snippets' conditions. Within each
2188 snippet-expansion routine like `yas-expand', computes actual
2189 value for the first time then always returns a cached value.")
2190 (setq body (cons doc body))
2192 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2193 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2194 (cdr timestamp-and-value)
2195 (let ((new-value (progn
2198 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2201 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2202 (defun yas-expand-from-trigger-key (&optional field)
2203 "Expand a snippet before point.
2205 If no snippet expansion is possible, fall back to the behaviour
2206 defined in `yas-fallback-behavior'.
2208 Optional argument FIELD is for non-interactive use and is an
2209 object satisfying `yas--field-p' to restrict the expansion to."
2211 (setq yas--condition-cache-timestamp (current-time))
2212 (let (templates-and-pos)
2213 (unless (and yas-expand-only-for-last-commands
2214 (not (member last-command yas-expand-only-for-last-commands)))
2215 (setq templates-and-pos (if field
2217 (narrow-to-region (yas--field-start field)
2218 (yas--field-end field))
2220 (yas--current-key))))
2221 (if (and templates-and-pos
2222 (first templates-and-pos))
2223 (yas--expand-or-prompt-for-template (first templates-and-pos)
2224 (second templates-and-pos)
2225 (third templates-and-pos))
2228 (defun yas-expand-from-keymap ()
2229 "Directly expand some snippets, searching `yas--direct-keymaps'.
2231 If expansion fails, execute the previous binding for this key"
2233 (setq yas--condition-cache-timestamp (current-time))
2234 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2235 (length (this-command-keys))
2237 (templates (mapcan #'(lambda (table)
2238 (yas--fetch table vec))
2239 (yas--get-snippet-tables))))
2241 (yas--expand-or-prompt-for-template templates)
2242 (let ((yas-fallback-behavior 'call-other-command))
2245 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2246 "Expand one of TEMPLATES from START to END.
2248 Prompt the user if TEMPLATES has more than one element, else
2249 expand immediately. Common gateway for
2250 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2251 (let ((yas--current-template (or (and (rest templates) ;; more than one
2252 (yas--prompt-for-template (mapcar #'cdr templates)))
2254 (when yas--current-template
2255 (yas-expand-snippet (yas--template-content yas--current-template)
2258 (yas--template-expand-env yas--current-template)))))
2260 ;; Apropos the trigger key and the fallback binding:
2262 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2263 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2264 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2265 ;; improve this explanation.
2267 (defun yas--fallback ()
2268 "Fallback after expansion has failed.
2270 Common gateway for `yas-expand-from-trigger-key' and
2271 `yas-expand-from-keymap'."
2272 (cond ((eq yas-fallback-behavior 'return-nil)
2275 ((eq yas-fallback-behavior 'call-other-command)
2276 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2277 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2278 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2279 (setq this-original-command beyond-yasnippet)
2280 (call-interactively beyond-yasnippet)))
2281 ((and (listp yas-fallback-behavior)
2282 (cdr yas-fallback-behavior)
2283 (eq 'apply (car yas-fallback-behavior)))
2284 (if (cddr yas-fallback-behavior)
2285 (apply (cadr yas-fallback-behavior)
2286 (cddr yas-fallback-behavior))
2287 (when (commandp (cadr yas-fallback-behavior))
2288 (setq this-command (cadr yas-fallback-behavior))
2289 (call-interactively (cadr yas-fallback-behavior)))))
2291 ;; also return nil if all the other fallbacks have failed
2294 (defun yas--keybinding-beyond-yasnippet ()
2296 (let* ((yas-minor-mode nil)
2297 (yas--direct-keymaps nil)
2298 (keys (this-single-command-keys)))
2299 (or (key-binding keys t)
2300 (key-binding (yas--fallback-translate-input keys) t))))
2302 (defun yas--fallback-translate-input (keys)
2303 "Emulate `read-key-sequence', at least what I think it does.
2305 Keys should be an untranslated key vector. Returns a translated
2306 vector of keys. FIXME not thoroughly tested."
2309 (while (< i (length keys))
2311 (translated local-function-key-map))
2312 (while (and (< j (length keys))
2314 (keymapp translated))
2315 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2317 (setq retval (vconcat retval (cond ((symbolp translated)
2319 ((vectorp translated)
2322 (substring keys i j)))))
2327 ;;; Utils for snippet development:
2329 (defun yas--all-templates (tables)
2330 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2332 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2333 `yas-buffer-local-condition'"
2334 (when yas-choose-tables-first
2335 (setq tables (list (yas--prompt-for-table tables))))
2337 (if yas-choose-keys-first
2338 (let ((key (yas--prompt-for-keys
2339 (mapcan #'yas--table-all-keys tables))))
2341 (mapcan #'(lambda (table)
2342 (yas--fetch table key))
2344 (remove-duplicates (mapcan #'yas--table-templates tables)
2347 (defun yas-insert-snippet (&optional no-condition)
2348 "Choose a snippet to expand, pop-up a list of choices according
2349 to `yas--prompt-function'.
2351 With prefix argument NO-CONDITION, bypass filtering of snippets
2354 (setq yas--condition-cache-timestamp (current-time))
2355 (let* ((yas-buffer-local-condition (or (and no-condition
2357 yas-buffer-local-condition))
2358 (templates (yas--all-templates (yas--get-snippet-tables)))
2359 (yas--current-template (and templates
2360 (or (and (rest templates) ;; more than one template for same key
2361 (yas--prompt-for-template templates))
2363 (where (if (region-active-p)
2364 (cons (region-beginning) (region-end))
2365 (cons (point) (point)))))
2366 (if yas--current-template
2367 (yas-expand-snippet (yas--template-content yas--current-template)
2370 (yas--template-expand-env yas--current-template))
2371 (yas--message 3 "No snippets can be inserted here!"))))
2373 (defun yas-visit-snippet-file ()
2374 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2376 Only success if selected snippet was loaded from a file. Put the
2377 visited file in `snippet-mode'."
2379 (let* ((yas-buffer-local-condition 'always)
2380 (templates (yas--all-templates (yas--get-snippet-tables)))
2381 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2382 (template (and templates
2383 (or (yas--prompt-for-template templates
2384 "Choose a snippet template to edit: ")
2388 (yas--visit-snippet-file-1 template)
2389 (message "No snippets tables active!"))))
2391 (defun yas--visit-snippet-file-1 (template)
2392 "Helper for `yas-visit-snippet-file'."
2393 (let ((file (yas--template-file template)))
2394 (cond ((and file (file-readable-p file))
2395 (find-file-other-window file)
2397 (set (make-local-variable 'yas--editing-template) template))
2399 (message "Original file %s no longer exists!" file))
2401 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2402 (let ((type 'snippet))
2403 (when (listp (yas--template-content template))
2404 (insert (format "# type: command\n"))
2405 (setq type 'command))
2406 (insert (format "# key: %s\n" (yas--template-key template)))
2407 (insert (format "# name: %s\n" (yas--template-name template)))
2408 (when (yas--template-keybinding template)
2409 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2410 (when (yas--template-expand-env template)
2411 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2412 (when (yas--template-condition template)
2413 (insert (format "# condition: %s\n" (yas--template-condition template))))
2415 (insert (if (eq type 'command)
2416 (pp-to-string (yas--template-content template))
2417 (yas--template-content template))))
2419 (set (make-local-variable 'yas--editing-template) template)))))
2421 (defun yas--guess-snippet-directories-1 (table)
2422 "Guess possible snippet subdirectories for TABLE."
2423 (cons (yas--table-name table)
2424 (mapcan #'(lambda (parent)
2425 (yas--guess-snippet-directories-1
2427 (yas--table-parents table))))
2429 (defun yas--guess-snippet-directories (&optional table)
2430 "Try to guess suitable directories based on the current active
2431 tables (or optional TABLE).
2433 Returns a list of elements (TABLE . DIRS) where TABLE is a
2434 `yas--table' object and DIRS is a list of all possible directories
2435 where snippets of table might exist."
2436 (let ((main-dir (replace-regexp-in-string
2438 (or (first (or (yas-snippet-dirs)
2439 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2440 (tables (or (and table
2442 (yas--get-snippet-tables))))
2443 ;; HACK! the snippet table created here is actually registered!
2445 (unless (or table (gethash major-mode yas--tables))
2446 (push (yas--table-get-create major-mode)
2449 (mapcar #'(lambda (table)
2451 (mapcar #'(lambda (subdir)
2452 (concat main-dir "/" subdir))
2453 (yas--guess-snippet-directories-1 table))))
2456 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2457 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2458 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2459 (let ((candidate (first (cdr table-and-dirs))))
2460 (unless (file-writable-p (file-name-directory candidate))
2461 (error (yas--format "%s is not writable." candidate)))
2462 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2464 (if (gethash (yas--table-mode (car table-and-dirs))
2468 (or main-table-string
2470 (yas--table-name (car table-and-dirs))))
2472 (make-directory candidate 'also-make-parents)
2473 ;; create the .yas-parents file here...
2476 (defun yas-new-snippet (&optional no-template)
2477 "Pops a new buffer for writing a snippet.
2479 Expands a snippet-writing snippet, unless the optional prefix arg
2480 NO-TEMPLATE is non-nil."
2482 (let ((guessed-directories (yas--guess-snippet-directories)))
2484 (switch-to-buffer "*new snippet*")
2486 (kill-all-local-variables)
2489 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2490 (yas--table-mode (car d)))
2491 guessed-directories))
2492 (if (and (not no-template) yas-new-snippet-default)
2493 (yas-expand-snippet yas-new-snippet-default))))
2495 (defun yas--compute-major-mode-and-parents (file)
2496 "Given FILE, find the nearest snippet directory for a given mode.
2498 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2499 representing one or more of the mode's parents.
2501 Note that MODE-SYM need not be the symbol of a real major mode,
2502 neither do the elements of PARENTS."
2503 (let* ((file-dir (and file
2504 (directory-file-name (or (some #'(lambda (special)
2505 (locate-dominating-file file special))
2509 (directory-file-name (file-name-directory file))))))
2510 (parents-file-name (concat file-dir "/.yas-parents"))
2511 (major-mode-name (and file-dir
2512 (file-name-nondirectory file-dir)))
2513 (major-mode-sym (or (and major-mode-name
2514 (intern major-mode-name))))
2515 (parents (when (file-readable-p parents-file-name)
2519 (insert-file-contents parents-file-name)
2520 (buffer-substring-no-properties (point-min)
2522 (when major-mode-sym
2523 (cons major-mode-sym (remove major-mode-sym parents)))))
2525 (defvar yas--editing-template nil
2526 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2528 (defvar yas--current-template nil
2529 "Holds the current template being expanded into a snippet.")
2531 (defvar yas--guessed-modes nil
2532 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2534 (defun yas--read-table ()
2535 "Ask user for a snippet table, help with some guessing."
2536 (let ((prompt (if (and (featurep 'ido)
2538 'ido-completing-read 'completing-read)))
2539 (unless yas--guessed-modes
2540 (set (make-local-variable 'yas--guessed-modes)
2541 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2543 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2544 (if yas--guessed-modes
2545 (first yas--guessed-modes)
2547 (mapcar #'symbol-name yas--guessed-modes)
2552 (if (first yas--guessed-modes)
2553 (symbol-name (first yas--guessed-modes)))))))
2555 (defun yas-load-snippet-buffer (table &optional interactive)
2556 "Parse and load current buffer's snippet definition into TABLE.
2558 TABLE is a symbol naming a passed to `yas--table-get-create'.
2560 When called interactively, prompt for the table name."
2561 (interactive (list (yas--read-table) t))
2563 ;; We have `yas--editing-template', this buffer's content comes from a
2564 ;; template which is already loaded and neatly positioned,...
2566 (yas--editing-template
2567 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2568 (yas--template-table yas--editing-template)))
2569 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2570 ;; value from `yas--compute-major-mode-and-parents'
2573 (unless yas--guessed-modes
2574 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2575 (let* ((table (yas--table-get-create table)))
2576 (set (make-local-variable 'yas--editing-template)
2577 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2580 (yas--message 3 "Snippet \"%s\" loaded for %s."
2581 (yas--template-name yas--editing-template)
2582 (yas--table-name (yas--template-table yas--editing-template)))))
2584 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2585 "Load the snippet with `yas-load-snippet-buffer', possibly
2586 save, then `quit-window' if saved.
2588 If the snippet is new, ask the user whether (and where) to save
2589 it. If the snippet already has a file, just save it.
2591 The prefix argument KILL is passed to `quit-window'.
2593 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2594 and `kill-buffer' instead."
2595 (interactive (list (yas--read-table) current-prefix-arg))
2596 (yas-load-snippet-buffer table t)
2598 ;; Only offer to save this if it looks like a library or new
2599 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2600 ;; which is not the first, or from an unwritable file)
2602 (not (yas--template-file yas--editing-template))
2603 (not (file-writable-p (yas--template-file yas--editing-template)))
2604 (and (listp yas-snippet-dirs)
2605 (second yas-snippet-dirs)
2606 (not (string-match (expand-file-name (first yas-snippet-dirs))
2607 (yas--template-file yas--editing-template)))))
2608 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2609 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2611 (yas--make-directory-maybe option))))
2613 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2614 (file-name-nondirectory (yas--template-file yas--editing-template)))
2615 (yas--template-name yas--editing-template))))
2616 (write-file (concat chosen "/"
2617 (read-from-minibuffer (format "File name to create in %s? " chosen)
2618 default-file-name)))
2619 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2620 (when buffer-file-name
2622 (quit-window kill)))
2624 (defun yas-tryout-snippet (&optional debug)
2625 "Test current buffer's snippet template in other buffer."
2627 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2628 (parsed (yas--parse-template))
2629 (test-mode (or (and (car major-mode-and-parent)
2630 (fboundp (car major-mode-and-parent))
2631 (car major-mode-and-parent))
2632 (first yas--guessed-modes)
2633 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2634 (yas--current-template
2637 (yas--populate-template (yas--make-blank-template)
2638 :table nil ;; no tables for ephemeral snippets
2640 :content (second parsed)
2641 :name (third parsed)
2642 :expand-env (sixth parsed)))))
2643 (cond (yas--current-template
2644 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2645 (kill-buffer (get-buffer-create buffer-name))
2646 (switch-to-buffer (get-buffer-create buffer-name))
2647 (setq buffer-undo-list nil)
2648 (condition-case nil (funcall test-mode) (error nil))
2650 (setq buffer-read-only nil)
2651 (yas-expand-snippet (yas--template-content yas--current-template)
2654 (yas--template-expand-env yas--current-template))
2656 (require 'yasnippet-debug nil t))
2657 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2659 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2661 (defun yas-active-keys ()
2662 "Return all active trigger keys for current buffer and point."
2664 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2667 (defun yas--template-fine-group (template)
2668 (car (last (or (yas--template-group template)
2669 (yas--template-perm-group template)))))
2671 (defun yas-describe-tables (&optional choose)
2672 "Display snippets for each table."
2674 (let* ((by-name-hash (and choose
2675 (y-or-n-p "Show by namehash? ")))
2676 (buffer (get-buffer-create "*YASnippet tables*"))
2677 (active-tables (yas--get-snippet-tables))
2678 (remain-tables (let ((all))
2679 (maphash #'(lambda (_k v)
2680 (unless (find v active-tables)
2684 (table-lists (list active-tables remain-tables))
2685 (original-buffer (current-buffer))
2687 (yas--condition-cache-timestamp (current-time)))
2688 (with-current-buffer buffer
2689 (setq buffer-read-only nil)
2691 (cond ((not by-name-hash)
2692 (insert "YASnippet tables: \n")
2693 (while (and table-lists
2695 (dolist (table (car table-lists))
2696 (yas--describe-pretty-table table original-buffer))
2697 (setq table-lists (cdr table-lists))
2699 (yas--create-snippet-xrefs)
2700 (display-buffer buffer)
2701 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2702 (yas--create-snippet-xrefs)
2706 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2707 (dolist (table (append active-tables remain-tables))
2708 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2710 (maphash #'(lambda (k _v)
2712 (yas--table-hash table))
2714 (insert (format " key %s maps snippets: %s\n" key
2716 (maphash #'(lambda (k _v)
2718 (gethash key (yas--table-hash table)))
2721 (setq buffer-read-only t))
2722 (display-buffer buffer)))
2724 (defun yas--describe-pretty-table (table &optional original-buffer)
2725 (insert (format "\nSnippet table `%s'"
2726 (yas--table-name table)))
2727 (if (yas--table-parents table)
2728 (insert (format " parents: %s\n"
2729 (mapcar #'yas--table-name
2730 (yas--table-parents table))))
2732 (insert (make-string 100 ?-) "\n")
2733 (insert "group state name key binding\n")
2734 (let ((groups-hash (make-hash-table :test #'equal)))
2735 (maphash #'(lambda (_k v)
2736 (let ((group (or (yas--template-fine-group v)
2738 (when (yas--template-name v)
2740 (cons v (gethash group groups-hash))
2742 (yas--table-uuidhash table))
2744 #'(lambda (group templates)
2745 (setq group (truncate-string-to-width group 25 0 ? "..."))
2746 (insert (make-string 100 ?-) "\n")
2747 (dolist (p templates)
2748 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2752 (setq group (make-string (length group) ? ))))
2753 (condition-string (let ((condition (yas--template-condition p)))
2756 (with-current-buffer original-buffer
2757 (if (yas--eval-condition condition)
2762 (insert condition-string " ")
2764 (if (string-match "\\.\\.\\.$" name)
2768 (insert (truncate-string-to-width (or (yas--template-key p) "")
2770 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2777 ;;; User convenience functions, for using in snippet definitions
2779 (defvar yas-modified-p nil
2780 "Non-nil if field has been modified by user or transformation.")
2782 (defvar yas-moving-away-p nil
2783 "Non-nil if user is about to exit field.")
2785 (defvar yas-text nil
2786 "Contains current field text.")
2788 (defun yas-substr (str pattern &optional subexp)
2789 "Search PATTERN in STR and return SUBEXPth match.
2791 If found, the content of subexp group SUBEXP (default 0) is
2792 returned, or else the original STR will be returned."
2793 (let ((grp (or subexp 0)))
2795 (if (string-match pattern str)
2796 (match-string-no-properties grp str)
2799 (defun yas-choose-value (&rest possibilities)
2800 "Prompt for a string in POSSIBILITIES and return it.
2802 The last element of POSSIBILITIES may be a list of strings."
2803 (unless (or yas-moving-away-p
2805 (setq possibilities (nreverse possibilities))
2806 (setq possibilities (if (listp (car possibilities))
2807 (append (reverse (car possibilities)) (rest possibilities))
2809 (some #'(lambda (fn)
2810 (funcall fn "Choose: " possibilities))
2811 yas-prompt-functions)))
2813 (defun yas-key-to-value (alist)
2814 (unless (or yas-moving-away-p
2816 (let ((key (read-key-sequence "")))
2818 (or (cdr (find key alist :key #'car :test #'string=))
2821 (defun yas-throw (text)
2822 "Throw a yas--exception with TEXT as the reason."
2823 (throw 'yas--exception (cons 'yas--exception text)))
2825 (defun yas-verify-value (possibilities)
2826 "Verify that the current field value is in POSSIBILITIES.
2828 Otherwise throw exception."
2829 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2830 (yas-throw (yas--format "Field only allows %s" possibilities))))
2832 (defun yas-field-value (number)
2833 "Get the string for field with NUMBER.
2835 Use this in primary and mirror transformations to tget."
2836 (let* ((snippet (car (yas--snippets-at-point)))
2838 (yas--snippet-find-field snippet number))))
2840 (yas--field-text-for-display field))))
2843 "Return `yas-text' if that exists and is non-empty, else nil."
2845 (not (string= "" yas-text)))
2848 (defun yas-selected-text ()
2849 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2850 (if (and yas-selected-text
2851 (not (string= "" yas-selected-text)))
2854 (defun yas--get-field-once (number &optional transform-fn)
2855 (unless yas-modified-p
2857 (funcall transform-fn (yas-field-value number))
2858 (yas-field-value number))))
2860 (defun yas-default-from-field (number)
2861 (unless yas-modified-p
2862 (yas-field-value number)))
2864 (defun yas-inside-string ()
2865 "Return non-nil if the point is inside a string according to font-lock."
2866 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2868 (defun yas-unimplemented (&optional missing-feature)
2869 (if yas--current-template
2870 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2873 (yas--visit-snippet-file-1 yas--current-template))
2874 (message "No implementation. Missing %s" (or missing-feature "something"))))
2877 ;;; Snippet expansion and field management
2879 (defvar yas--active-field-overlay nil
2880 "Overlays the currently active field.")
2882 (defvar yas--field-protection-overlays nil
2883 "Two overlays protect the current active field.")
2885 (defvar yas-selected-text nil
2886 "The selected region deleted on the last snippet expansion.")
2888 (defvar yas--start-column nil
2889 "The column where the snippet expansion started.")
2891 (make-variable-buffer-local 'yas--active-field-overlay)
2892 (make-variable-buffer-local 'yas--field-protection-overlays)
2893 (put 'yas--active-field-overlay 'permanent-local t)
2894 (put 'yas--field-protection-overlays 'permanent-local t)
2896 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2902 (id (yas--snippet-next-id) :read-only t)
2903 (control-overlay nil)
2905 ;; stacked expansion: the `previous-active-field' slot saves the
2906 ;; active field where the child expansion took place
2907 previous-active-field
2910 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2913 NUMBER is the field number.
2914 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2915 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2916 MIRRORS is a list of `yas--mirror's
2917 TRANSFORM is a lisp form.
2918 MODIFIED-P is a boolean set to true once user inputs text.
2919 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2930 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2933 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2934 TRANSFORM is a lisp form.
2935 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2936 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2937 DEPTH is a count of how many nested mirrors can affect this mirror"
2944 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2948 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2949 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2951 If there is no transform for ht field, return nil.
2953 If there is a transform but it returns nil, return the empty
2954 string iff EMPTY-ON-NIL-P is true."
2955 (let* ((yas-text (yas--field-text-for-display field))
2956 (yas-modified-p (yas--field-modified-p field))
2957 (yas-moving-away-p nil)
2958 (transform (if (yas--mirror-p field-or-mirror)
2959 (yas--mirror-transform field-or-mirror)
2960 (yas--field-transform field-or-mirror)))
2961 (start-point (if (yas--mirror-p field-or-mirror)
2962 (yas--mirror-start field-or-mirror)
2963 (yas--field-start field-or-mirror)))
2964 (transformed (and transform
2966 (goto-char start-point)
2967 (let ((ret (yas--eval-lisp transform)))
2968 (or ret (and empty-on-nil-p "")))))))
2971 (defsubst yas--replace-all (from to &optional text)
2972 "Replace all occurrences from FROM to TO.
2974 With optional string TEXT do it in that string."
2976 (replace-regexp-in-string (regexp-quote from) to text t t)
2977 (goto-char (point-min))
2978 (while (search-forward from nil t)
2979 (replace-match to t t text))))
2981 (defun yas--snippet-find-field (snippet number)
2982 (find-if #'(lambda (field)
2983 (eq number (yas--field-number field)))
2984 (yas--snippet-fields snippet)))
2986 (defun yas--snippet-sort-fields (snippet)
2987 "Sort the fields of SNIPPET in navigation order."
2988 (setf (yas--snippet-fields snippet)
2989 (sort (yas--snippet-fields snippet)
2990 #'yas--snippet-field-compare)))
2992 (defun yas--snippet-field-compare (field1 field2)
2993 "Compare FIELD1 and FIELD2.
2995 The field with a number is sorted first. If they both have a
2996 number, compare through the number. If neither have, compare
2997 through the field's start point"
2998 (let ((n1 (yas--field-number field1))
2999 (n2 (yas--field-number field2)))
3002 (or (zerop n2) (and (not (zerop n1))
3007 (< (yas--field-start field1)
3008 (yas--field-start field2))))))
3010 (defun yas--field-probably-deleted-p (snippet field)
3011 "Guess if SNIPPET's FIELD should be skipped."
3013 ;; field must be zero length
3015 (zerop (- (yas--field-start field) (yas--field-end field)))
3018 ;; 1) is a nested field and it's been modified
3020 (and (yas--field-parent-field field)
3021 (yas--field-modified-p field))
3022 ;; 2) ends just before the snippet end
3024 (and (eq field (car (last (yas--snippet-fields snippet))))
3025 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3026 ;; the field numbered 0, just before the exit marker, should
3029 (not (zerop (yas--field-number field)))))
3031 (defun yas--snippets-at-point (&optional all-snippets)
3032 "Return a sorted list of snippets at point.
3034 The most recently-inserted snippets are returned first."
3036 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3037 (overlay-get ov 'yas--snippet))
3039 (overlays-in (point-min) (point-max))
3040 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3042 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3044 (defun yas-next-field-or-maybe-expand ()
3045 "Try to expand a snippet at a key before point.
3047 Otherwise delegate to `yas-next-field'."
3049 (if yas-triggers-in-field
3050 (let ((yas-fallback-behavior 'return-nil)
3051 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3053 (unless (yas-expand-from-trigger-key active-field)
3057 (defun yas-next-field (&optional arg)
3058 "Navigate to the ARGth next field.
3060 If there's none, exit the snippet."
3064 (snippet (first (yas--snippets-at-point)))
3065 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3066 (live-fields (remove-if #'(lambda (field)
3067 (and (not (eq field active-field))
3068 (yas--field-probably-deleted-p snippet field)))
3069 (yas--snippet-fields snippet)))
3070 (active-field-pos (position active-field live-fields))
3071 (target-pos (and active-field-pos (+ arg active-field-pos)))
3072 (target-field (and target-pos (nth target-pos live-fields))))
3073 ;; First check if we're moving out of a field with a transform
3075 (when (and active-field
3076 (yas--field-transform active-field))
3077 (let* ((yas-moving-away-p t)
3078 (yas-text (yas--field-text-for-display active-field))
3079 (yas-modified-p (yas--field-modified-p active-field)))
3080 ;; primary field transform: exit call to field-transform
3081 (yas--eval-lisp (yas--field-transform active-field))))
3082 ;; Now actually move...
3083 (cond ((and target-pos (>= target-pos (length live-fields)))
3084 (yas-exit-snippet snippet))
3086 (yas--move-to-field snippet target-field))
3090 (defun yas--place-overlays (snippet field)
3091 "Correctly place overlays for SNIPPET's FIELD."
3092 (yas--make-move-field-protection-overlays snippet field)
3093 (yas--make-move-active-field-overlay snippet field))
3095 (defun yas--move-to-field (snippet field)
3096 "Update SNIPPET to move to field FIELD.
3098 Also create some protection overlays"
3099 (goto-char (yas--field-start field))
3100 (yas--place-overlays snippet field)
3101 (overlay-put yas--active-field-overlay 'yas--field field)
3102 (let ((number (yas--field-number field)))
3103 ;; check for the special ${0: ...} field
3104 (if (and number (zerop number))
3106 (set-mark (yas--field-end field))
3107 (setf (yas--snippet-force-exit snippet)
3108 (or (yas--field-transform field)
3110 ;; make this field active
3111 (setf (yas--snippet-active-field snippet) field)
3112 ;; primary field transform: first call to snippet transform
3113 (unless (yas--field-modified-p field)
3114 (if (yas--field-update-display field)
3115 (yas--update-mirrors snippet)
3116 (setf (yas--field-modified-p field) nil))))))
3118 (defun yas-prev-field ()
3119 "Navigate to prev field. If there's none, exit the snippet."
3121 (yas-next-field -1))
3123 (defun yas-abort-snippet (&optional snippet)
3125 (let ((snippet (or snippet
3126 (car (yas--snippets-at-point)))))
3128 (setf (yas--snippet-force-exit snippet) t))))
3130 (defun yas-exit-snippet (snippet)
3131 "Goto exit-marker of SNIPPET."
3132 (interactive (list (first (yas--snippets-at-point))))
3134 (setf (yas--snippet-force-exit snippet) t)
3135 (goto-char (if (yas--snippet-exit snippet)
3136 (yas--exit-marker (yas--snippet-exit snippet))
3137 (overlay-end (yas--snippet-control-overlay snippet))))))
3139 (defun yas-exit-all-snippets ()
3140 "Exit all snippets."
3142 (mapc #'(lambda (snippet)
3143 (yas-exit-snippet snippet)
3144 (yas--check-commit-snippet))
3145 (yas--snippets-at-point 'all-snippets)))
3148 ;;; Some low level snippet-routines:
3150 (defvar yas--inhibit-overlay-hooks nil
3151 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3153 (defmacro yas--inhibit-overlay-hooks (&rest body)
3154 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3155 (declare (indent 0))
3156 `(let ((yas--inhibit-overlay-hooks t))
3159 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3160 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3162 (defun yas--commit-snippet (snippet)
3163 "Commit SNIPPET, but leave point as it is.
3165 This renders the snippet as ordinary text."
3167 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3169 ;; Save the end of the moribund snippet in case we need to revive it
3170 ;; its original expansion.
3172 (when (and control-overlay
3173 (overlay-buffer control-overlay))
3174 (setq yas-snippet-beg (overlay-start control-overlay))
3175 (setq yas-snippet-end (overlay-end control-overlay))
3176 (delete-overlay control-overlay))
3178 (yas--inhibit-overlay-hooks
3179 (when yas--active-field-overlay
3180 (delete-overlay yas--active-field-overlay))
3181 (when yas--field-protection-overlays
3182 (mapc #'delete-overlay yas--field-protection-overlays)))
3184 ;; stacked expansion: if the original expansion took place from a
3185 ;; field, make sure we advance it here at least to
3186 ;; `yas-snippet-end'...
3188 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3189 (when (and yas-snippet-end previous-field)
3190 (yas--advance-end-maybe previous-field yas-snippet-end)))
3192 ;; Convert all markers to points,
3194 (yas--markers-to-points snippet)
3196 ;; Take care of snippet revival
3198 (if yas-snippet-revival
3199 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3201 ;; Dismember the snippet... this is useful if we get called
3202 ;; again from `yas--take-care-of-redo'....
3203 (setf (yas--snippet-fields snippet) nil)))
3205 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3207 (defun yas--safely-run-hooks (hook-var)
3208 (condition-case error
3209 (run-hooks hook-var)
3211 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3214 (defun yas--check-commit-snippet ()
3215 "Check if point exited the currently active field of the snippet.
3217 If so cleans up the whole snippet up."
3218 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3219 (snippets-left snippets)
3220 (snippet-exit-transform))
3221 (dolist (snippet snippets)
3222 (let ((active-field (yas--snippet-active-field snippet)))
3223 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3224 (cond ((or snippet-exit-transform
3225 (not (and active-field (yas--field-contains-point-p active-field))))
3226 (setq snippets-left (delete snippet snippets-left))
3227 (setf (yas--snippet-force-exit snippet) nil)
3228 (yas--commit-snippet snippet))
3230 (or (not yas--active-field-overlay)
3231 (not (overlay-buffer yas--active-field-overlay))))
3233 ;; stacked expansion: this case is mainly for recent
3234 ;; snippet exits that place us back int the field of
3238 (yas--move-to-field snippet active-field)
3239 (yas--update-mirrors snippet)))
3242 (unless (or (null snippets) snippets-left)
3243 (if snippet-exit-transform
3244 (yas--eval-lisp-no-saves snippet-exit-transform))
3245 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3247 ;; Apropos markers-to-points:
3249 ;; This was found useful for performance reasons, so that an
3250 ;; excessive number of live markers aren't kept around in the
3251 ;; `buffer-undo-list'. However, in `markers-to-points', the
3252 ;; set-to-nil markers can't simply be discarded and replaced with
3253 ;; fresh ones in `points-to-markers'. The original marker that was
3254 ;; just set to nil has to be reused.
3256 ;; This shouldn't bring horrible problems with undo/redo, but it
3259 (defun yas--markers-to-points (snippet)
3260 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3261 where POINT is the original position of the marker and MARKER is
3262 the original marker object with the position set to nil."
3263 (dolist (field (yas--snippet-fields snippet))
3264 (let ((start (marker-position (yas--field-start field)))
3265 (end (marker-position (yas--field-end field))))
3266 (set-marker (yas--field-start field) nil)
3267 (set-marker (yas--field-end field) nil)
3268 (setf (yas--field-start field) (cons start (yas--field-start field)))
3269 (setf (yas--field-end field) (cons end (yas--field-end field))))
3270 (dolist (mirror (yas--field-mirrors field))
3271 (let ((start (marker-position (yas--mirror-start mirror)))
3272 (end (marker-position (yas--mirror-end mirror))))
3273 (set-marker (yas--mirror-start mirror) nil)
3274 (set-marker (yas--mirror-end mirror) nil)
3275 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3276 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3277 (let ((snippet-exit (yas--snippet-exit snippet)))
3279 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3280 (set-marker (yas--exit-marker snippet-exit) nil)
3281 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3283 (defun yas--points-to-markers (snippet)
3284 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3286 This is done by setting MARKER to POINT with `set-marker'."
3287 (dolist (field (yas--snippet-fields snippet))
3288 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3289 (car (yas--field-start field))))
3290 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3291 (car (yas--field-end field))))
3292 (dolist (mirror (yas--field-mirrors field))
3293 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3294 (car (yas--mirror-start mirror))))
3295 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3296 (car (yas--mirror-end mirror))))))
3297 (let ((snippet-exit (yas--snippet-exit snippet)))
3299 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3300 (car (yas--exit-marker snippet-exit)))))))
3302 (defun yas--field-contains-point-p (field &optional point)
3303 (let ((point (or point
3305 (and (>= point (yas--field-start field))
3306 (<= point (yas--field-end field)))))
3308 (defun yas--field-text-for-display (field)
3309 "Return the propertized display text for field FIELD."
3310 (buffer-substring (yas--field-start field) (yas--field-end field)))
3312 (defun yas--undo-in-progress ()
3313 "True if some kind of undo is in progress."
3314 (or undo-in-progress
3315 (eq this-command 'undo)
3316 (eq this-command 'redo)))
3318 (defun yas--make-control-overlay (snippet start end)
3319 "Create the control overlay that surrounds the snippet and
3321 (let ((overlay (make-overlay start
3326 (overlay-put overlay 'keymap yas-keymap)
3327 (overlay-put overlay 'priority 100)
3328 (overlay-put overlay 'yas--snippet snippet)
3331 (defun yas-skip-and-clear-or-delete-char (&optional field)
3332 "Clears unmodified field if at field start, skips to next tab.
3334 Otherwise deletes a character normally by calling `delete-char'."
3336 (let ((field (or field
3337 (and yas--active-field-overlay
3338 (overlay-buffer yas--active-field-overlay)
3339 (overlay-get yas--active-field-overlay 'yas--field)))))
3341 (not (yas--field-modified-p field))
3342 (eq (point) (marker-position (yas--field-start field))))
3343 (yas--skip-and-clear field)
3346 (call-interactively 'delete-char)))))
3348 (defun yas--skip-and-clear (field)
3349 "Deletes the region of FIELD and sets it's modified state to t."
3350 ;; Just before skipping-and-clearing the field, mark its children
3351 ;; fields as modified, too. If the children have mirrors-in-fields
3352 ;; this prevents them from updating erroneously (we're skipping and
3355 (yas--mark-this-and-children-modified field)
3356 (delete-region (yas--field-start field) (yas--field-end field)))
3358 (defun yas--mark-this-and-children-modified (field)
3359 (setf (yas--field-modified-p field) t)
3360 (let ((fom (yas--field-next field)))
3362 (yas--fom-parent-field fom))
3363 (when (and (eq (yas--fom-parent-field fom) field)
3365 (yas--mark-this-and-children-modified fom))
3366 (setq fom (yas--fom-next fom)))))
3368 (defun yas--make-move-active-field-overlay (snippet field)
3369 "Place the active field overlay in SNIPPET's FIELD.
3371 Move the overlay, or create it if it does not exit."
3372 (if (and yas--active-field-overlay
3373 (overlay-buffer yas--active-field-overlay))
3374 (move-overlay yas--active-field-overlay
3375 (yas--field-start field)
3376 (yas--field-end field))
3377 (setq yas--active-field-overlay
3378 (make-overlay (yas--field-start field)
3379 (yas--field-end field)
3381 (overlay-put yas--active-field-overlay 'priority 100)
3382 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3383 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3384 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3385 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3386 '(yas--on-field-overlay-modification))
3387 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3388 '(yas--on-field-overlay-modification))))
3390 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3391 "Clears the field and updates mirrors, conditionally.
3393 Only clears the field if it hasn't been modified and it point it
3394 at field start. This hook doesn't do anything if an undo is in
3396 (unless (or yas--inhibit-overlay-hooks
3397 (yas--undo-in-progress))
3398 (let* ((field (overlay-get overlay 'yas--field))
3399 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3401 (yas--advance-end-maybe field (overlay-end overlay))
3403 (yas--field-update-display field))
3404 (yas--update-mirrors snippet))
3406 (when (and (not after?)
3407 (not (yas--field-modified-p field))
3408 (eq (point) (if (markerp (yas--field-start field))
3409 (marker-position (yas--field-start field))
3410 (yas--field-start field))))
3411 (yas--skip-and-clear field))
3412 (setf (yas--field-modified-p field) t))))))
3414 ;;; Apropos protection overlays:
3416 ;; These exist for nasty users who will try to delete parts of the
3417 ;; snippet outside the active field. Actual protection happens in
3418 ;; `yas--on-protection-overlay-modification'.
3420 ;; Currently this signals an error which inhibits the command. For
3421 ;; commands that move point (like `kill-line'), point is restored in
3422 ;; the `yas--post-command-handler' using a global
3423 ;; `yas--protection-violation' variable.
3425 ;; Alternatively, I've experimented with an implementation that
3426 ;; commits the snippet before actually calling `this-command'
3427 ;; interactively, and then signals an error, which is ignored. but
3428 ;; blocks all other million modification hooks. This presented some
3429 ;; problems with stacked expansion.
3431 (defun yas--make-move-field-protection-overlays (snippet field)
3432 "Place protection overlays surrounding SNIPPET's FIELD.
3434 Move the overlays, or create them if they do not exit."
3435 (let ((start (yas--field-start field))
3436 (end (yas--field-end field)))
3437 ;; First check if the (1+ end) is contained in the buffer,
3438 ;; otherwise we'll have to do a bit of cheating and silently
3439 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3440 ;; when using stacked expansion
3442 (when (< (buffer-size) end)
3444 (yas--inhibit-overlay-hooks
3445 (goto-char (point-max))
3447 ;; go on to normal overlay creation/moving
3449 (cond ((and yas--field-protection-overlays
3450 (every #'overlay-buffer yas--field-protection-overlays))
3451 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3452 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3454 (setq yas--field-protection-overlays
3455 (list (make-overlay (1- start) start nil t nil)
3456 (make-overlay end (1+ end) nil t nil)))
3457 (dolist (ov yas--field-protection-overlays)
3458 (overlay-put ov 'face 'yas--field-debug-face)
3459 (overlay-put ov 'yas--snippet snippet)
3460 ;; (overlay-put ov 'evaporate t)
3461 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3463 (defvar yas--protection-violation nil
3464 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3466 Functions in the `post-command-hook', for example
3467 `yas--post-command-handler' can check it and reset its value to
3468 nil. The variables value is the point where the violation
3471 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3472 "Signals a snippet violation, then issues error.
3474 The error should be ignored in `debug-ignored-errors'"
3475 (unless yas--inhibit-overlay-hooks
3476 (cond ((not (or after?
3477 (yas--undo-in-progress)))
3478 (setq yas--protection-violation (point))
3479 (error "Exit the snippet first!")))))
3481 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3484 ;;; Snippet expansion and "stacked" expansion:
3486 ;; Stacked expansion is when you try to expand a snippet when already
3487 ;; inside a snippet expansion.
3489 ;; The parent snippet does not run its fields modification hooks
3490 ;; (`yas--on-field-overlay-modification' and
3491 ;; `yas--on-protection-overlay-modification') while the child snippet
3492 ;; is active. This means, among other things, that the mirrors of the
3493 ;; parent snippet are not updated, this only happening when one exits
3494 ;; the child snippet.
3496 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3497 ;; bits of code in `yas-expand-snippet' and
3498 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3501 ;; This was thought to be safer in an undo/redo perspective, but
3502 ;; maybe the correct implementation is to make the globals
3503 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3504 ;; snippet-local and be active even while the child snippet is
3505 ;; running. This would mean a lot of overlay modification hooks
3506 ;; running, but if managed correctly (including overlay priorities)
3507 ;; they should account for all situations...
3509 (defun yas-expand-snippet (content &optional start end expand-env)
3510 "Expand snippet CONTENT at current point.
3512 Text between START and END will be deleted before inserting
3513 template. EXPAND-ENV is are let-style variable to value bindings
3514 considered when expanding the snippet."
3515 (run-hooks 'yas-before-expand-snippet-hook)
3518 (let* ((yas-selected-text (or yas-selected-text
3519 (and (region-active-p)
3520 (buffer-substring-no-properties (region-beginning)
3523 (and (region-active-p)
3527 (and (region-active-p)
3530 (to-delete (and start
3532 (buffer-substring-no-properties start end)))
3535 (setq yas--indent-original-column (current-column))
3536 ;; Delete the region to delete, this *does* get undo-recorded.
3538 (when (and to-delete
3540 (delete-region start end))
3542 (cond ((listp content)
3543 ;; x) This is a snippet-command
3545 (yas--eval-lisp-no-saves content))
3547 ;; x) This is a snippet-snippet :-)
3549 ;; Narrow the region down to the content, shoosh the
3550 ;; `buffer-undo-list', and create the snippet, the new
3551 ;; snippet updates its mirrors once, so we are left with
3552 ;; some plain text. The undo action for deleting this
3553 ;; plain text will get recorded at the end.
3555 ;; stacked expansion: also shoosh the overlay modification hooks
3556 (let ((buffer-undo-list t))
3557 ;; snippet creation might evaluate users elisp, which
3558 ;; might generate errors, so we have to be ready to catch
3559 ;; them mostly to make the undo information
3561 (setq yas--start-column (current-column))
3562 (yas--inhibit-overlay-hooks
3565 (eval `(let* ,expand-env
3567 (yas--snippet-create start (point))))
3569 (yas--snippet-create start (point))))))
3571 ;; stacked-expansion: This checks for stacked expansion, save the
3572 ;; `yas--previous-active-field' and advance its boundary.
3574 (let ((existing-field (and yas--active-field-overlay
3575 (overlay-buffer yas--active-field-overlay)
3576 (overlay-get yas--active-field-overlay 'yas--field))))
3577 (when existing-field
3578 (setf (yas--snippet-previous-active-field snippet) existing-field)
3579 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3581 ;; Exit the snippet immediately if no fields
3583 (unless (yas--snippet-fields snippet)
3584 (yas-exit-snippet snippet))
3586 ;; Push two undo actions: the deletion of the inserted contents of
3587 ;; the new snippet (without the "key") followed by an apply of
3588 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3590 ;; A small exception, if `yas-also-auto-indent-first-line'
3591 ;; is t and `yas--indent' decides to indent the line to a
3592 ;; point before the actual expansion point, undo would be
3593 ;; messed up. We call the early point "newstart"". case,
3594 ;; and attempt to fix undo.
3596 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3597 (end (overlay-end (yas--snippet-control-overlay snippet))))
3598 (when (< newstart start)
3599 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3600 (push (cons newstart end) buffer-undo-list)
3601 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3603 ;; Now, schedule a move to the first field
3605 (let ((first-field (car (yas--snippet-fields snippet))))
3607 (sit-for 0) ;; fix issue 125
3608 (yas--move-to-field snippet first-field)))
3609 (yas--message 3 "snippet expanded.")
3612 (defun yas--take-care-of-redo (_beg _end snippet)
3613 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3615 Meant to exit in the `buffer-undo-list'."
3616 ;; slightly optimize: this action is only needed for snippets with
3617 ;; at least one field
3618 (when (yas--snippet-fields snippet)
3619 (yas--commit-snippet snippet)))
3621 (defun yas--snippet-revive (beg end snippet)
3622 "Revives SNIPPET and creates a control overlay from BEG to END.
3624 BEG and END are, we hope, the original snippets boundaries.
3625 All the markers/points exiting existing inside SNIPPET should point
3626 to their correct locations *at the time the snippet is revived*.
3628 After revival, push the `yas--take-care-of-redo' in the
3630 ;; Reconvert all the points to markers
3632 (yas--points-to-markers snippet)
3633 ;; When at least one editable field existed in the zombie snippet,
3634 ;; try to revive the whole thing...
3636 (let ((target-field (or (yas--snippet-active-field snippet)
3637 (car (yas--snippet-fields snippet)))))
3639 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3640 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3642 (yas--move-to-field snippet target-field)
3644 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3645 buffer-undo-list))))
3647 (defun yas--snippet-create (begin end)
3648 "Create a snippet from a template inserted at BEGIN to END.
3650 Returns the newly created snippet."
3652 (narrow-to-region begin end)
3653 (let ((snippet (yas--make-snippet)))
3655 (yas--snippet-parse-create snippet)
3657 ;; Sort and link each field
3658 (yas--snippet-sort-fields snippet)
3660 ;; Create keymap overlay for snippet
3661 (setf (yas--snippet-control-overlay snippet)
3662 (yas--make-control-overlay snippet (point-min) (point-max)))
3665 (goto-char (point-max))
3670 ;;; Apropos adjacencies and "fom's":
3672 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3673 ;; recently expanded snippet, we might actually have many fields,
3674 ;; mirrors (and the snippet exit) in the very same position in the
3675 ;; buffer. Therefore we need to single-link the
3676 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3677 ;; according to their original positions in the buffer.
3679 ;; Then we have operation `yas--advance-end-maybe' and
3680 ;; `yas--advance-start-maybe', which conditionally push the starts and
3681 ;; ends of these foms down the chain.
3683 ;; This allows for like the printf with the magic ",":
3685 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3686 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3688 (defun yas--fom-start (fom)
3689 (cond ((yas--field-p fom)
3690 (yas--field-start fom))
3691 ((yas--mirror-p fom)
3692 (yas--mirror-start fom))
3694 (yas--exit-marker fom))))
3696 (defun yas--fom-end (fom)
3697 (cond ((yas--field-p fom)
3698 (yas--field-end fom))
3699 ((yas--mirror-p fom)
3700 (yas--mirror-end fom))
3702 (yas--exit-marker fom))))
3704 (defun yas--fom-next (fom)
3705 (cond ((yas--field-p fom)
3706 (yas--field-next fom))
3707 ((yas--mirror-p fom)
3708 (yas--mirror-next fom))
3710 (yas--exit-next fom))))
3712 (defun yas--fom-parent-field (fom)
3713 (cond ((yas--field-p fom)
3714 (yas--field-parent-field fom))
3715 ((yas--mirror-p fom)
3716 (yas--mirror-parent-field fom))
3720 (defun yas--calculate-adjacencies (snippet)
3721 "Calculate adjacencies for fields or mirrors of SNIPPET.
3723 This is according to their relative positions in the buffer, and
3724 has to be called before the $-constructs are deleted."
3725 (let* ((fom-set-next-fom
3726 (lambda (fom nextfom)
3727 (cond ((yas--field-p fom)
3728 (setf (yas--field-next fom) nextfom))
3729 ((yas--mirror-p fom)
3730 (setf (yas--mirror-next fom) nextfom))
3732 (setf (yas--exit-next fom) nextfom)))))
3735 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3736 (yas--mirror-p fom2)
3737 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3738 (link-foms fom-set-next-fom))
3739 ;; make some yas--field, yas--mirror and yas--exit soup
3741 (when (yas--snippet-exit snippet)
3742 (push (yas--snippet-exit snippet) soup))
3743 (dolist (field (yas--snippet-fields snippet))
3745 (dolist (mirror (yas--field-mirrors field))
3746 (push mirror soup)))
3748 (sort soup compare-fom-begs))
3750 (reduce link-foms soup)))))
3752 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3753 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3755 Use the tightest containing field if more than one field contains
3756 the mirror. Intended to be called *before* the dollar-regions are
3758 (let ((min (point-min))
3760 (dolist (field (yas--snippet-fields snippet))
3761 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3762 (<= (yas--mirror-end mirror) (yas--field-end field))
3763 (< min (yas--field-start field))
3764 (< (yas--field-end field) max))
3765 (setq min (yas--field-start field)
3766 max (yas--field-end field))
3767 (setf (yas--mirror-parent-field mirror) field)))))
3769 (defun yas--advance-end-maybe (fom newend)
3770 "Maybe advance FOM's end to NEWEND if it needs it.
3774 * call `yas--advance-start-maybe' on FOM's next fom.
3776 * in case FOM is field call `yas--advance-end-maybe' on its parent
3779 Also, if FOM is an exit-marker, always call
3780 `yas--advance-start-maybe' on its next fom. This is because
3781 exit-marker have identical start and end markers."
3782 (cond ((and fom (< (yas--fom-end fom) newend))
3783 (set-marker (yas--fom-end fom) newend)
3784 (yas--advance-start-maybe (yas--fom-next fom) newend)
3785 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3787 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3789 (defun yas--advance-start-maybe (fom newstart)
3790 "Maybe advance FOM's start to NEWSTART if it needs it.
3792 If it does, also call `yas--advance-end-maybe' on FOM."
3793 (when (and fom (< (yas--fom-start fom) newstart))
3794 (set-marker (yas--fom-start fom) newstart)
3795 (yas--advance-end-maybe fom newstart)))
3797 (defun yas--advance-end-of-parents-maybe (field newend)
3798 "Like `yas--advance-end-maybe' but for parent fields.
3800 Only works for fields and doesn't care about the start of the
3801 next FOM. Works its way up recursively for parents of parents."
3803 (< (yas--field-end field) newend))
3804 (set-marker (yas--field-end field) newend)
3805 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3807 (defvar yas--dollar-regions nil
3808 "When expanding the snippet the \"parse-create\" functions add
3809 cons cells to this var.")
3811 (defvar yas--backquote-markers-and-strings nil
3812 "List of (MARKER . STRING) marking where the values from
3813 backquoted Lisp expressions should be inserted at the end of
3816 (defun yas--snippet-parse-create (snippet)
3817 "Parse a recently inserted snippet template, creating all
3818 necessary fields, mirrors and exit points.
3820 Meant to be called in a narrowed buffer, does various passes"
3821 (let ((parse-start (point)))
3822 ;; Reset the yas--dollar-regions
3824 (setq yas--dollar-regions nil)
3825 ;; protect just the backquotes
3827 (yas--protect-escapes nil '(?`))
3828 ;; replace all backquoted expressions
3830 (goto-char parse-start)
3831 (yas--save-backquotes)
3832 ;; protect escaped characters
3834 (yas--protect-escapes)
3835 ;; parse fields with {}
3837 (goto-char parse-start)
3838 (yas--field-parse-create snippet)
3839 ;; parse simple mirrors and fields
3841 (goto-char parse-start)
3842 (yas--simple-mirror-parse-create snippet)
3843 ;; parse mirror transforms
3845 (goto-char parse-start)
3846 (yas--transform-mirror-parse-create snippet)
3847 ;; calculate adjacencies of fields and mirrors
3849 (yas--calculate-adjacencies snippet)
3850 ;; Delete $-constructs
3852 (save-restriction (widen) (yas--delete-regions yas--dollar-regions))
3853 ;; restore backquoted expression values
3855 (yas--restore-backquotes)
3858 (goto-char parse-start)
3859 (yas--restore-escapes)
3860 ;; update mirrors for the first time
3862 (yas--update-mirrors snippet)
3863 ;; indent the best we can
3865 (goto-char parse-start)
3866 (yas--indent snippet)))
3868 (defun yas--indent-according-to-mode (snippet-markers)
3869 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3870 ;;; Apropos indenting problems....
3872 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3873 ;; is available. Some implementations of these functions delete text
3874 ;; before they insert. If there happens to be a marker just after
3875 ;; the text being deleted, the insertion actually happens after the
3876 ;; marker, which misplaces it.
3878 ;; This would also happen if we had used overlays with the
3879 ;; `front-advance' property set to nil.
3881 ;; This is why I have these `trouble-markers', they are the ones at
3882 ;; they are the ones at the first non-whitespace char at the line
3883 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3884 ;; we should be at the correct to restore them to. All other
3885 ;; non-trouble-markers have been *pushed* and don't need special
3888 (goto-char (yas--real-line-beginning))
3889 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3895 (indent-according-to-mode)
3896 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3898 (mapc #'(lambda (marker)
3899 (set-marker marker (point)))
3902 (defvar yas--indent-original-column nil)
3903 (defun yas--indent (snippet)
3904 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3905 ;; Look for those $>
3907 (while (re-search-forward "$>" nil t)
3908 (delete-region (match-beginning 0) (match-end 0))
3909 (when (not (eq yas-indent-line 'auto))
3910 (yas--indent-according-to-mode snippet-markers))))
3911 ;; Now do stuff for 'fixed and 'auto
3913 (cond ((eq yas-indent-line 'fixed)
3914 (while (and (zerop (forward-line))
3915 (zerop (current-column)))
3916 (indent-to-column yas--indent-original-column)))
3917 ((eq yas-indent-line 'auto)
3918 (let ((end (set-marker (make-marker) (point-max)))
3919 (indent-first-line-p yas-also-auto-indent-first-line))
3920 (while (and (zerop (if indent-first-line-p
3923 (setq indent-first-line-p nil))
3927 (yas--indent-according-to-mode snippet-markers))))
3931 (defun yas--collect-snippet-markers (snippet)
3932 "Make a list of all the markers used by SNIPPET."
3934 (dolist (field (yas--snippet-fields snippet))
3935 (push (yas--field-start field) markers)
3936 (push (yas--field-end field) markers)
3937 (dolist (mirror (yas--field-mirrors field))
3938 (push (yas--mirror-start mirror) markers)
3939 (push (yas--mirror-end mirror) markers)))
3940 (let ((snippet-exit (yas--snippet-exit snippet)))
3941 (when (and snippet-exit
3942 (marker-buffer (yas--exit-marker snippet-exit)))
3943 (push (yas--exit-marker snippet-exit) markers)))
3946 (defun yas--real-line-beginning ()
3947 (let ((c (char-after (line-beginning-position)))
3948 (n (line-beginning-position)))
3949 (while (or (eql c ?\ )
3952 (setq c (char-after n)))
3955 (defun yas--escape-string (escaped)
3956 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3958 (defun yas--protect-escapes (&optional text escaped)
3959 "Protect all escaped characters with their numeric ASCII value.
3961 With optional string TEXT do it in string instead of buffer."
3962 (let ((changed-text text)
3963 (text-provided-p text))
3964 (mapc #'(lambda (escaped)
3966 (yas--replace-all (concat "\\" (char-to-string escaped))
3967 (yas--escape-string escaped)
3968 (when text-provided-p changed-text))))
3969 (or escaped yas--escaped-characters))
3972 (defun yas--restore-escapes (&optional text escaped)
3973 "Restore all escaped characters from their numeric ASCII value.
3975 With optional string TEXT do it in string instead of the buffer."
3976 (let ((changed-text text)
3977 (text-provided-p text))
3978 (mapc #'(lambda (escaped)
3980 (yas--replace-all (yas--escape-string escaped)
3981 (char-to-string escaped)
3982 (when text-provided-p changed-text))))
3983 (or escaped yas--escaped-characters))
3986 (defun yas--save-backquotes ()
3987 "Save all the \"`(lisp-expression)`\"-style expressions
3988 with their evaluated value into `yas--backquote-markers-and-strings'."
3989 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3990 (let ((current-string (match-string-no-properties 1)) transformed)
3991 (delete-region (match-beginning 0) (match-end 0))
3992 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3993 (goto-char (match-beginning 0))
3995 (let ((marker (make-marker)))
3996 (insert "Y") ;; quite horrendous, I love it :)
3997 (set-marker marker (point))
3999 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4001 (defun yas--restore-backquotes ()
4002 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4003 (while yas--backquote-markers-and-strings
4004 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4005 (marker (car marker-and-string))
4006 (string (cdr marker-and-string)))
4012 (set-marker marker nil)))))
4014 (defun yas--scan-sexps (from count)
4016 (with-syntax-table (standard-syntax-table)
4017 (scan-sexps from count))
4021 (defun yas--make-marker (pos)
4022 "Create a marker at POS with nil `marker-insertion-type'."
4023 (let ((marker (set-marker (make-marker) pos)))
4024 (set-marker-insertion-type marker nil)
4027 (defun yas--field-parse-create (snippet &optional parent-field)
4028 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4030 The following count as a field:
4032 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4034 * \"${n: text$(expression)}, the same with a Lisp expression;
4035 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4037 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4039 When multiple expressions are found, only the last one counts."
4042 (while (re-search-forward yas--field-regexp nil t)
4043 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4044 (number (and (match-string-no-properties 1)
4045 (string-to-number (match-string-no-properties 1))))
4046 (brand-new-field (and real-match-end-0
4047 ;; break if on "$(" immediately
4048 ;; after the ":", this will be
4049 ;; caught as a mirror with
4051 (not (save-match-data
4052 (eq (string-match "$[ \t\n]*("
4053 (match-string-no-properties 2)) 0)))
4054 ;; allow ${0: some exit text}
4055 ;; (not (and number (zerop number)))
4056 (yas--make-field number
4057 (yas--make-marker (match-beginning 2))
4058 (yas--make-marker (1- real-match-end-0))
4060 (when brand-new-field
4061 (goto-char real-match-end-0)
4062 (push (cons (1- real-match-end-0) real-match-end-0)
4063 yas--dollar-regions)
4064 (push (cons (match-beginning 0) (match-beginning 2))
4065 yas--dollar-regions)
4066 (push brand-new-field (yas--snippet-fields snippet))
4069 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4070 (goto-char (point-min))
4071 (yas--field-parse-create snippet brand-new-field)))))))
4072 ;; if we entered from a parent field, now search for the
4073 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4074 ;; primary field transformations
4078 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4079 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4080 ;; commit the primary field transformation if:
4082 ;; 1. we don't find it in yas--dollar-regions (a subnested
4083 ;; field) might have already caught it.
4085 ;; 2. we really make sure we have either two '$' or some
4086 ;; text and a '$' after the colon ':'. This is a FIXME: work
4087 ;; my regular expressions and end these ugly hacks.
4089 (when (and real-match-end-1
4090 (not (member (cons (match-beginning 0)
4092 yas--dollar-regions))
4094 (char-before (1- (match-beginning 1))))))
4095 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4097 (setf (yas--field-transform parent-field)
4098 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4099 (push (cons (match-beginning 0) real-match-end-1)
4100 yas--dollar-regions)))))))
4102 (defun yas--transform-mirror-parse-create (snippet)
4103 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4104 (while (re-search-forward yas--transform-mirror-regexp nil t)
4105 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4106 (number (string-to-number (match-string-no-properties 1)))
4108 (not (zerop number))
4109 (yas--snippet-find-field snippet number)))
4111 (and real-match-end-0
4113 (yas--make-mirror (yas--make-marker (match-beginning 0))
4114 (yas--make-marker (match-beginning 0))
4116 (yas--restore-escapes
4117 (buffer-substring-no-properties (match-beginning 2)
4118 (1- real-match-end-0))))))))
4119 (when brand-new-mirror
4120 (push brand-new-mirror
4121 (yas--field-mirrors field))
4122 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4123 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4125 (defun yas--simple-mirror-parse-create (snippet)
4126 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4127 (while (re-search-forward yas--simple-mirror-regexp nil t)
4128 (let ((number (string-to-number (match-string-no-properties 1))))
4129 (cond ((zerop number)
4131 (setf (yas--snippet-exit snippet)
4132 (yas--make-exit (yas--make-marker (match-end 0))))
4134 (goto-char (match-beginning 0))
4135 (when yas-wrap-around-region
4136 (cond (yas-selected-text
4137 (insert yas-selected-text))
4138 ((and (eq yas-wrap-around-region 'cua)
4141 (insert (prog1 (get-register ?0)
4142 (set-register ?0 nil))))))
4143 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4144 yas--dollar-regions)))
4146 (let ((field (yas--snippet-find-field snippet number)))
4148 (let ((brand-new-mirror (yas--make-mirror
4149 (yas--make-marker (match-beginning 0))
4150 (yas--make-marker (match-beginning 0))
4152 (push brand-new-mirror
4153 (yas--field-mirrors field))
4154 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4155 (push (yas--make-field number
4156 (yas--make-marker (match-beginning 0))
4157 (yas--make-marker (match-beginning 0))
4159 (yas--snippet-fields snippet))))
4160 (push (cons (match-beginning 0) (match-end 0))
4161 yas--dollar-regions))))))
4163 (defun yas--delete-regions (regions)
4164 "Sort disjuct REGIONS by start point, then delete from the back."
4165 (mapc #'(lambda (reg)
4166 (delete-region (car reg) (cdr reg)))
4169 (>= (car r1) (car r2))))))
4171 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4172 (let* ((parent (yas--mirror-parent-field mirror))
4173 (parents-mirrors (and parent
4174 (yas--field-mirrors parent))))
4175 (or (yas--mirror-depth mirror)
4176 (setf (yas--mirror-depth mirror)
4177 (cond ((memq mirror traversed)
4179 ((and parent parents-mirrors)
4181 (mapcar #'(lambda (m)
4182 (yas--calculate-mirror-depth m
4191 (defun yas--update-mirrors (snippet)
4192 "Update all the mirrors of SNIPPET."
4194 (dolist (field-and-mirror (sort
4195 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4196 ;; where F is the field that M is mirroring
4198 (mapcan #'(lambda (field)
4199 (mapcar #'(lambda (mirror)
4200 (cons field mirror))
4201 (yas--field-mirrors field)))
4202 (yas--snippet-fields snippet))
4203 ;; then sort this list so that entries with mirrors with parent
4204 ;; fields appear before. This was important for fixing #290, and
4205 ;; luckily also handles the case where a mirror in a field causes
4206 ;; another mirror to need reupdating
4208 #'(lambda (field-and-mirror1 field-and-mirror2)
4209 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4210 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4211 (let* ((field (car field-and-mirror))
4212 (mirror (cdr field-and-mirror))
4213 (parent-field (yas--mirror-parent-field mirror)))
4214 ;; before updating a mirror with a parent-field, maybe advance
4218 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4219 ;; update this mirror
4221 (yas--mirror-update-display mirror field)
4222 ;; `yas--place-overlays' is needed if the active field and
4223 ;; protected overlays have been changed because of insertions
4224 ;; in `yas--mirror-update-display'
4226 (when (eq field (yas--snippet-active-field snippet))
4227 (yas--place-overlays snippet field))))))
4229 (defun yas--mirror-update-display (mirror field)
4230 "Update MIRROR according to FIELD (and mirror transform)."
4232 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4233 (reflection (and (not (and mirror-parent-field
4234 (yas--field-modified-p mirror-parent-field)))
4235 (or (yas--apply-transform mirror field 'empty-on-nil)
4236 (yas--field-text-for-display field)))))
4237 (when (and reflection
4238 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4239 (yas--mirror-end mirror)))))
4240 (goto-char (yas--mirror-start mirror))
4241 (yas--inhibit-overlay-hooks
4242 (insert reflection))
4243 (if (> (yas--mirror-end mirror) (point))
4244 (delete-region (point) (yas--mirror-end mirror))
4245 (set-marker (yas--mirror-end mirror) (point))
4246 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4247 ;; super-special advance
4248 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4250 (defun yas--field-update-display (field)
4251 "Much like `yas--mirror-update-display', but for fields."
4252 (when (yas--field-transform field)
4253 (let ((transformed (and (not (eq (yas--field-number field) 0))
4254 (yas--apply-transform field field))))
4255 (when (and transformed
4256 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4257 (yas--field-end field)))))
4258 (setf (yas--field-modified-p field) t)
4259 (goto-char (yas--field-start field))
4260 (yas--inhibit-overlay-hooks
4261 (insert transformed)
4262 (if (> (yas--field-end field) (point))
4263 (delete-region (point) (yas--field-end field))
4264 (set-marker (yas--field-end field) (point))
4265 (yas--advance-start-maybe (yas--field-next field) (point)))
4269 ;;; Post-command hook:
4271 (defun yas--post-command-handler ()
4272 "Handles various yasnippet conditions after each command."
4273 (cond (yas--protection-violation
4274 (goto-char yas--protection-violation)
4275 (setq yas--protection-violation nil))
4276 ((eq 'undo this-command)
4278 ;; After undo revival the correct field is sometimes not
4279 ;; restored correctly, this condition handles that
4281 (let* ((snippet (car (yas--snippets-at-point)))
4282 (target-field (and snippet
4283 (find-if-not #'(lambda (field)
4284 (yas--field-probably-deleted-p snippet field))
4286 (cons (yas--snippet-active-field snippet)
4287 (yas--snippet-fields snippet)))))))
4289 (yas--move-to-field snippet target-field))))
4290 ((not (yas--undo-in-progress))
4291 ;; When not in an undo, check if we must commit the snippet
4292 ;; (user exited it).
4293 (yas--check-commit-snippet))))
4297 ;; The docstrings for some functions are generated dynamically
4298 ;; depending on the context.
4300 (put 'yas-expand 'function-documentation
4301 '(yas--expand-from-trigger-key-doc))
4302 (defun yas--expand-from-trigger-key-doc ()
4303 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4304 (let ((fallback-description
4305 (cond ((eq yas-fallback-behavior 'call-other-command)
4306 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4308 (format " call command `%s'." (pp-to-string fallback)))
4309 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4310 ((eq yas-fallback-behavior 'return-nil)
4313 ", defer to `yas-fallback-behaviour' (which see)"))))
4314 (concat "Expand a snippet before point. If no snippet
4315 expansion is possible,"
4316 fallback-description
4317 "\n\nOptional argument FIELD is for non-interactive use and is an
4318 object satisfying `yas--field-p' to restrict the expansion to.")))
4320 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4321 (defun yas--expand-from-keymap-doc ()
4322 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4323 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4324 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4325 (when (eq this-command 'describe-key)
4326 (let* ((vec (this-single-command-keys))
4327 (templates (mapcan #'(lambda (table)
4328 (yas--fetch table vec))
4329 (yas--get-snippet-tables)))
4330 (yas--direct-keymaps nil)
4331 (fallback (key-binding vec)))
4332 (concat "In this case, "
4334 (concat "these snippets are bound to this key:\n"
4335 (yas--template-pretty-list templates)
4336 "\n\nIf none of these expands, "))
4338 (format "fallback `%s' will be called." (pp-to-string fallback)))
4339 "no fallback keybinding is called."))))))
4341 (defun yas--template-pretty-list (templates)
4343 (yas-buffer-local-condition 'always))
4344 (dolist (plate templates)
4345 (setq acc (concat acc "\n*) "
4346 (propertize (concat "\\\\snippet `" (car plate) "'")
4347 'yasnippet (cdr plate)))))
4350 (define-button-type 'help-snippet-def
4351 :supertype 'help-xref
4352 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4353 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4355 (defun yas--snippet-description-finish-runonce ()
4356 "Final adjustments for the help buffer when snippets are concerned."
4357 (yas--create-snippet-xrefs)
4358 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4360 (defun yas--create-snippet-xrefs ()
4362 (goto-char (point-min))
4363 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4364 (let ((template (get-text-property (match-beginning 1)
4367 (help-xref-button 1 'help-snippet-def template)
4368 (kill-region (match-end 1) (match-end 0))
4369 (kill-region (match-beginning 0) (match-beginning 1)))))))
4373 (defvar yas-verbosity 4
4374 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4376 (defun yas--message (level message &rest args)
4377 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4378 (when (> yas-verbosity level)
4379 (message "%s" (apply #'yas--format message args))))
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--exported-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
4529 yas-default-from-field
4532 yas-define-condition-cache
4533 yas-hippie-try-expand
4536 ;; debug definitions
4537 ;; yas-debug-snippet-vars
4538 ;; yas-exterminate-package
4541 ;; testing definitions
4542 ;; yas-should-expand
4543 ;; yas-should-not-expand
4545 ;; yas-make-file-or-dirs
4547 ;; yas-saving-variables
4548 ;; yas-call-with-snippet-dirs
4549 ;; yas-with-snippet-dirs
4551 "Exported yasnippet symbols.
4553 i.e. ones that I will try to keep in future yasnippet versions
4554 and ones that other elisp libraries can more or less safely rely
4557 (defvar yas--dont-backport '(yas-active-keys)
4558 "Exported symbols that don't map back to \"yas/*\" variants.")
4560 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4561 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4563 (make-obsolete-variable backported sym "yasnippet 0.8")
4564 (defvaralias backported sym))
4566 (make-obsolete backported sym "yasnippet 0.8")
4567 (defalias backported sym))))
4570 (provide 'yasnippet)
4572 ;;; yasnippet.el ends here
4575 ;; byte-compile-warnings: (not cl-functions)