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.
53 ;; A local variable that you can set in a hook to override
54 ;; snippet-lookup based on major mode. It is a list of
55 ;; symbols that correspond to subdirectories of
56 ;; `yas-snippet-dirs' and is used for deciding which
57 ;; snippets to consider for the active buffer.
59 ;; Major commands are:
63 ;; Try to expand snippets before point. In `yas-minor-mode',
64 ;; this is normally bound to TAB, but you can customize it in
65 ;; `yas-minor-mode-map'.
67 ;; M-x yas-load-directory
69 ;; Prompts you for a directory hierarchy of snippets to load.
71 ;; M-x yas-insert-snippet
73 ;; Prompts you for possible snippet expansion if that is
74 ;; possible according to buffer-local and snippet-local
75 ;; expansion conditions. With prefix argument, ignore these
78 ;; M-x yas-visit-snippet-file
80 ;; Prompts you for possible snippet expansions like
81 ;; `yas-insert-snippet', but instead of expanding it, takes
82 ;; you directly to the snippet definition's file, if it
85 ;; M-x yas-new-snippet
87 ;; Lets you create a new snippet file in the correct
88 ;; subdirectory of `yas-snippet-dirs', according to the
91 ;; M-x yas-load-snippet-buffer
93 ;; When editing a snippet, this loads the snippet. This is
94 ;; bound to "C-c C-c" while in the `snippet-mode' editing
97 ;; M-x yas-tryout-snippet
99 ;; When editing a snippet, this opens a new empty buffer,
100 ;; sets it to the appropriate major mode and inserts the
101 ;; snippet there, so you can see what it looks like. This is
102 ;; bound to "C-c C-t" while in `snippet-mode'.
104 ;; M-x yas-describe-tables
106 ;; Lists known snippets in a separate buffer. User is
107 ;; prompted as to whether only the currently active tables
108 ;; are to be displayed, or all the tables for all major
111 ;; If you have `dropdown-list' installed, you can optionally use it
112 ;; as the preferred "prompting method", putting in your .emacs file,
115 ;; (require 'dropdown-list)
116 ;; (setq yas-prompt-functions '(yas-dropdown-prompt
118 ;; yas-completing-prompt))
120 ;; Also check out the customization group
122 ;; M-x customize-group RET yasnippet RET
124 ;; If you use the customization group to set variables
125 ;; `yas-snippet-dirs' or `yas-global-mode', make sure the path to
126 ;; "yasnippet.el" is present in the `load-path' *before* the
127 ;; `custom-set-variables' is executed in your .emacs file.
129 ;; For more information and detailed usage, refer to the project page:
130 ;; http://github.com/capitaomorte/yasnippet
138 (defvar yas--editing-template)
139 (defvar yas--guessed-modes)
140 (defvar yas--indent-original-column)
141 (defvar yas--scheduled-jit-loads)
143 (defvar yas-selected-text)
144 (defvar yas-verbosity)
145 (defvar yas--current-template)
148 ;;; User customizable variables
150 (defgroup yasnippet nil
151 "Yet Another Snippet extension"
154 (defvar yas--load-file-name load-file-name
155 "Store the filename that yasnippet.el was originally loaded from.")
157 (defcustom yas-snippet-dirs (remove nil
158 (list "~/.emacs.d/snippets"
159 (when yas--load-file-name
160 (concat (file-name-directory yas--load-file-name) "snippets"))))
161 "Directory or list of snippet dirs for each major mode.
163 The directory where user-created snippets are to be stored. Can
164 also be a list of directories. In that case, when used for
165 bulk (re)loading of snippets (at startup or via
166 `yas-reload-all'), directories appearing earlier in the list
167 shadow other dir's snippets. Also, the first directory is taken
168 as the default for storing the user's new snippets."
169 :type '(choice (string :tag "Single directory (string)")
170 (repeat :args (string) :tag "List of directories (strings)"))
173 :set #'(lambda (symbol new)
174 (let ((old (and (boundp symbol)
175 (symbol-value symbol))))
176 (set-default symbol new)
177 (unless (or (not (fboundp 'yas-reload-all))
181 (defun yas-snippet-dirs ()
182 "Return `yas-snippet-dirs' (which see) as a list."
183 (if (listp yas-snippet-dirs) yas-snippet-dirs (list yas-snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas-snippet-dirs)
187 (defcustom yas-new-snippet-default "\
188 # -*- mode: snippet -*-
190 # key: ${2:${1:$(yas--key-from-desc yas-text)}}${3:
191 # binding: ${4:direct-keybinding}}${5:
192 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
196 "Default snippet to use when creating a new snippet.
197 If nil, don't use any snippet."
201 (defcustom yas-prompt-functions '(yas-x-prompt
203 yas-completing-prompt
206 "Functions to prompt for keys, templates, etc interactively.
208 These functions are called with the following arguments:
210 - PROMPT: A string to prompt the user
212 - CHOICES: a list of strings or objects.
214 - optional DISPLAY-FN : A function that, when applied to each of
215 the objects in CHOICES will return a string.
217 The return value of any function you put here should be one of
218 the objects in CHOICES, properly formatted with DISPLAY-FN (if
221 - To signal that your particular style of prompting is
222 unavailable at the moment, you can also have the function return
225 - To signal that the user quit the prompting process, you can
228 (signal 'quit \"user quit!\")."
229 :type '(repeat function)
232 (defcustom yas-indent-line 'auto
233 "Controls indenting applied to a recent snippet expansion.
235 The following values are possible:
237 - `fixed' Indent the snippet to the current column;
239 - `auto' Indent each line of the snippet with `indent-according-to-mode'
241 Every other value means don't apply any snippet-side indentation
242 after expansion (the manual per-line \"$>\" indentation still
244 :type '(choice (const :tag "Nothing" nothing)
245 (const :tag "Fixed" fixed)
246 (const :tag "Auto" auto))
249 (defcustom yas-also-auto-indent-first-line nil
250 "Non-nil means also auto indent first line according to mode.
252 Naturally this is only valid when `yas-indent-line' is `auto'"
256 (defcustom yas-snippet-revival t
257 "Non-nil means re-activate snippet fields after undo/redo."
261 (defcustom yas-triggers-in-field nil
262 "If non-nil, allow stacked expansions (snippets inside snippets).
264 Otherwise `yas-next-field-or-maybe-expand' just moves on to the
269 (defcustom yas-fallback-behavior 'call-other-command
270 "How to act when `yas-expand' does *not* expand a snippet.
272 - `call-other-command' means try to temporarily disable YASnippet
273 and call the next command bound to whatever key was used to
276 - nil or the symbol `return-nil' mean do nothing. (and
277 `yas-expand' returns nil)
279 - A Lisp form (apply COMMAND . ARGS) means interactively call
280 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
281 with ARGS as arguments."
282 :type '(choice (const :tag "Call previous command" call-other-command)
283 (const :tag "Do nothing" return-nil))
286 (defcustom yas-choose-keys-first nil
287 "If non-nil, prompt for snippet key first, then for template.
289 Otherwise prompts for all possible snippet names.
291 This affects `yas-insert-snippet' and `yas-visit-snippet-file'."
295 (defcustom yas-choose-tables-first nil
296 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
298 Otherwise, user chooses between the merging together of all
301 This affects `yas-insert-snippet', `yas-visit-snippet-file'"
305 (defcustom yas-use-menu 'abbreviate
306 "Display a YASnippet menu in the menu bar.
308 When non-nil, submenus for each snippet table will be listed
309 under the menu \"Yasnippet\".
311 - If set to `abbreviate', only the current major-mode
312 menu and the modes set in `yas-extra-modes' are listed.
314 - If set to `full', every submenu is listed
316 - It set to nil, don't display a menu at all (this requires a
317 `yas-reload-all' call if the menu is already visible).
319 Any other non-nil value, every submenu is listed."
320 :type '(choice (const :tag "Full" full)
321 (const :tag "Abbreviate" abbreviate)
322 (const :tag "No menu" nil))
325 (defcustom yas-trigger-symbol (or (and (eq window-system 'mac)
327 (char-to-string ?\x21E5))) ;; little ->| sign
329 "The text that will be used in menu to represent the trigger."
333 (defcustom yas-wrap-around-region nil
334 "If non-nil, snippet expansion wraps around selected region.
336 The wrapping occurs just before the snippet's exit marker. This
337 can be overridden on a per-snippet basis."
341 (defcustom yas-good-grace t
342 "If non-nil, don't raise errors in inline elisp evaluation.
344 An error string \"[yas] error\" is returned instead."
348 (defcustom yas-visit-from-menu nil
349 "If non-nil visit snippets's files from menu, instead of expanding them.
351 This can only work when snippets are loaded from files."
355 (defcustom yas-expand-only-for-last-commands nil
356 "List of `last-command' values to restrict tab-triggering to, or nil.
358 Leave this set at nil (the default) to be able to trigger an
359 expansion simply by placing the cursor after a valid tab trigger,
360 using whichever commands.
362 Optionally, set this to something like '(self-insert-command) if
363 you to wish restrict expansion to only happen when the last
364 letter of the snippet tab trigger was typed immediately before
365 the trigger key itself."
366 :type '(repeat function)
369 ;; Only two faces, and one of them shouldn't even be used...
371 (defface yas-field-highlight-face
372 '((t (:inherit 'region)))
373 "The face used to highlight the currently active field of a snippet"
376 (defface yas--field-debug-face
378 "The face used for debugging some overlays normally hidden"
382 ;;; User-visible variables
384 (defvar yas-keymap (let ((map (make-sparse-keymap)))
385 (define-key map [(tab)] 'yas-next-field-or-maybe-expand)
386 (define-key map (kbd "TAB") 'yas-next-field-or-maybe-expand)
387 (define-key map [(shift tab)] 'yas-prev-field)
388 (define-key map [backtab] 'yas-prev-field)
389 (define-key map (kbd "C-g") 'yas-abort-snippet)
390 (define-key map (kbd "C-d") 'yas-skip-and-clear-or-delete-char)
392 "The active keymap while a snippet expansion is in progress.")
394 (defvar yas-key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
395 "List of character syntaxes used to find a trigger key before point.
396 The list is tried in the order while scanning characters
397 backwards from point. For example, if the list is '(\"w\" \"w_\")
398 first look for trigger keys which are composed exclusively of
399 \"word\"-syntax characters, and then, if that fails, look for
400 keys which are either of \"word\" or \"symbol\"
401 syntax. Triggering after
405 will, according to the \"w\" element first try \"bar\". If that
406 isn't a trigger key, \"foo-bar\" is tried, respecting a second
409 (defvar yas-after-exit-snippet-hook
411 "Hooks to run after a snippet exited.
413 The hooks will be run in an environment where some variables bound to
416 `yas-snippet-beg' : The beginning of the region of the snippet.
418 `yas-snippet-end' : Similar to beg.
420 Attention: These hooks are not run when exiting nested/stacked snippet expansion!")
422 (defvar yas-before-expand-snippet-hook
424 "Hooks to run just before expanding a snippet.")
426 (defvar yas-buffer-local-condition
427 '(if (and (or (fourth (syntax-ppss))
428 (fifth (syntax-ppss)))
430 (eq this-command 'yas-expand-from-trigger-key))
431 '(require-snippet-condition . force-in-comment)
433 "Snippet expanding condition.
435 This variable is a Lisp form which is evaluated every time a
436 snippet expansion is attempted:
438 * If it evaluates to nil, no snippets can be expanded.
440 * If it evaluates to the a cons (require-snippet-condition
443 * Snippets bearing no \"# condition:\" directive are not
446 * Snippets bearing conditions that evaluate to nil (or
447 produce an error) won't be considered.
449 * If the snippet has a condition that evaluates to non-nil
452 * If REQUIREMENT is t, the snippet is considered
454 * If REQUIREMENT is `eq' RESULT, the snippet is
457 * Otherwise, the snippet is not considered.
459 * If it evaluates to the symbol 'always, all snippets are
460 considered for expansion, regardless of any conditions.
462 * If it evaluates to t or some other non-nil value
464 * Snippet bearing no conditions, or conditions that
465 evaluate to non-nil, are considered for expansion.
467 * Otherwise, the snippet is not considered.
469 Here's an example preventing snippets from being expanded from
470 inside comments, in `python-mode' only, with the exception of
471 snippets returning the symbol 'force-in-comment in their
474 (add-hook 'python-mode-hook
476 (setq yas-buffer-local-condition
477 '(if (python-in-string/comment)
478 '(require-snippet-condition . force-in-comment)
481 The default value is similar, it filters out potential snippet
482 expansions inside comments and string literals, unless the
483 snippet itself contains a condition that returns the symbol
484 `force-in-comment'.")
487 ;;; Internal variables
489 (defvar yas--version "0.8.0beta")
491 (defvar yas--menu-table (make-hash-table)
492 "A hash table of MAJOR-MODE symbols to menu keymaps.")
494 (defvar yas--known-modes
495 '(ruby-mode rst-mode markdown-mode)
496 "A list of mode which is well known but not part of Emacs.")
498 (defvar yas--escaped-characters
499 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
500 "List of characters which *might* need to be escaped.")
502 (defconst yas--field-regexp
503 "${\\([0-9]+:\\)?\\([^}]*\\)}"
504 "A regexp to *almost* recognize a field.")
506 (defconst yas--multi-dollar-lisp-expression-regexp
507 "$+[ \t\n]*\\(([^)]*)\\)"
508 "A regexp to *almost* recognize a \"$(...)\" expression.")
510 (defconst yas--backquote-lisp-expression-regexp
512 "A regexp to recognize a \"`lisp-expression`\" expression." )
514 (defconst yas--transform-mirror-regexp
515 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
516 "A regexp to *almost* recognize a mirror with a transform.")
518 (defconst yas--simple-mirror-regexp
520 "A regexp to recognize a simple mirror.")
522 (defvar yas--snippet-id-seed 0
523 "Contains the next id for a snippet.")
525 (defun yas--snippet-next-id ()
526 (let ((id yas--snippet-id-seed))
527 (incf yas--snippet-id-seed)
533 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
534 (defvar last-buffer-undo-list nil)
536 (defvar yas--minor-mode-menu nil
537 "Holds the YASnippet menu.")
539 (defun yas--init-minor-keymap ()
540 "Set up the `yas-minor-mode' keymap."
541 (let ((map (make-sparse-keymap)))
543 (easy-menu-define yas--minor-mode-menu
545 "Menu used when `yas-minor-mode' is active."
548 ["Expand trigger" yas-expand
549 :help "Possibly expand tab trigger before point"]
550 ["Insert at point..." yas-insert-snippet
551 :help "Prompt for an expandable snippet and expand it at point"]
552 ["New snippet..." yas-new-snippet
553 :help "Create a new snippet in an appropriate directory"]
554 ["Visit snippet file..." yas-visit-snippet-file
555 :help "Prompt for an expandable snippet and find its file"]
557 ("Snippet menu behaviour"
558 ["Visit snippets" (setq yas-visit-from-menu t)
559 :help "Visit snippets from the menu"
560 :active t :style radio :selected yas-visit-from-menu]
561 ["Expand snippets" (setq yas-visit-from-menu nil)
562 :help "Expand snippets from the menu"
563 :active t :style radio :selected (not yas-visit-from-menu)]
565 ["Show all known modes" (setq yas-use-menu 'full)
566 :help "Show one snippet submenu for each loaded table"
567 :active t :style radio :selected (eq yas-use-menu 'full)]
568 ["Abbreviate according to current mode" (setq yas-use-menu 'abbreviate)
569 :help "Show only snippet submenus for the current active modes"
570 :active t :style radio :selected (eq yas-use-menu 'abbreviate)])
572 ["Auto" (setq yas-indent-line 'auto)
573 :help "Indent each line of the snippet with `indent-according-to-mode'"
574 :active t :style radio :selected (eq yas-indent-line 'auto)]
575 ["Fixed" (setq yas-indent-line 'fixed)
576 :help "Indent the snippet to the current column"
577 :active t :style radio :selected (eq yas-indent-line 'fixed)]
578 ["None" (setq yas-indent-line 'none)
579 :help "Don't apply any particular snippet indentation after expansion"
580 :active t :style radio :selected (not (member yas-indent-line '(fixed auto)))]
582 ["Also auto indent first line" (setq yas-also-auto-indent-first-line
583 (not yas-also-auto-indent-first-line))
584 :help "When auto-indenting also, auto indent the first line menu"
585 :active (eq yas-indent-line 'auto)
586 :style toggle :selected yas-also-auto-indent-first-line]
589 ["System X-widget" (setq yas-prompt-functions
591 (remove 'yas-x-prompt
592 yas-prompt-functions)))
593 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
594 :active t :style radio :selected (eq (car yas-prompt-functions)
596 ["Dropdown-list" (setq yas-prompt-functions
597 (cons 'yas-dropdown-prompt
598 (remove 'yas-dropdown-prompt
599 yas-prompt-functions)))
600 :help "Use a special dropdown list"
601 :active t :style radio :selected (eq (car yas-prompt-functions)
602 'yas-dropdown-prompt)]
603 ["Ido" (setq yas-prompt-functions
604 (cons 'yas-ido-prompt
605 (remove 'yas-ido-prompt
606 yas-prompt-functions)))
607 :help "Use an ido-style minibuffer prompt"
608 :active t :style radio :selected (eq (car yas-prompt-functions)
610 ["Completing read" (setq yas-prompt-functions
611 (cons 'yas-completing-prompt
612 (remove 'yas-completing-prompt
613 yas-prompt-functions)))
614 :help "Use a normal minibuffer prompt"
615 :active t :style radio :selected (eq (car yas-prompt-functions)
616 'yas-completing-prompt)]
619 ["Wrap region in exit marker"
620 (setq yas-wrap-around-region
621 (not yas-wrap-around-region))
622 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
623 :style toggle :selected yas-wrap-around-region]
624 ["Allow stacked expansions "
625 (setq yas-triggers-in-field
626 (not yas-triggers-in-field))
627 :help "If non-nil allow snippets to be triggered inside other snippet fields"
628 :style toggle :selected yas-triggers-in-field]
629 ["Revive snippets on undo "
630 (setq yas-snippet-revival
631 (not yas-snippet-revival))
632 :help "If non-nil allow snippets to become active again after undo"
633 :style toggle :selected yas-snippet-revival]
636 (not yas-good-grace))
637 :help "If non-nil don't raise errors in bad embedded elisp in snippets"
638 :style toggle :selected yas-good-grace]
641 ["Load snippets..." yas-load-directory
642 :help "Load snippets from a specific directory"]
643 ["Reload everything" yas-reload-all
644 :help "Cleanup stuff, reload snippets, rebuild menus"]
646 :help "Display some information about YASnippet"])))
648 ;; Now for the stuff that has direct keybindings
650 (define-key map [(tab)] 'yas-expand)
651 (define-key map (kbd "TAB") 'yas-expand)
652 (define-key map "\C-c&\C-s" 'yas-insert-snippet)
653 (define-key map "\C-c&\C-n" 'yas-new-snippet)
654 (define-key map "\C-c&\C-v" 'yas-visit-snippet-file)
657 (defvar yas-minor-mode-map (yas--init-minor-keymap)
658 "The keymap used when `yas-minor-mode' is active.")
660 (defvar yas-extra-modes nil
661 "A list of modes for which to also lookup snippets.
663 This variable probably makes more sense as buffer-local, so
664 ensure your use `make-local-variable' when you set it.")
666 (defvar yas--tables (make-hash-table)
667 "A hash table of mode symbols to `yas--table' objects.")
669 (defvar yas--parents (make-hash-table)
670 "A hash table of mode symbols do lists of direct parent mode symbols.
672 This list is populated when reading the \".yas-parents\" files
673 found when traversing snippet directories with
674 `yas-load-directory'.
676 There might be additional parenting information stored in the
677 `derived-mode-parent' property of some mode symbols, but that is
680 (defvar yas--direct-keymaps (list)
681 "Keymap alist supporting direct snippet keybindings.
683 This variable is placed in `emulation-mode-map-alists'.
685 Its elements looks like (TABLE-NAME . KEYMAP). They're
686 instantiated on `yas-reload-all' but KEYMAP is added to only when
687 loading snippets. `yas--direct-TABLE-NAME' is then a variable set
688 buffer-locally when entering `yas-minor-mode'. KEYMAP binds all
689 defined direct keybindings to the command
690 `yas-expand-from-keymap' which then which snippet to expand.")
692 (defun yas-direct-keymaps-reload ()
693 "Force reload the direct keybinding for active snippet tables."
695 (setq yas--direct-keymaps nil)
696 (maphash #'(lambda (name table)
697 (push (cons (intern (format "yas--direct-%s" name))
698 (yas--table-direct-keymap table))
699 yas--direct-keymaps))
702 (defun yas--modes-to-activate ()
703 "Compute list of mode symbols that are active for `yas-expand'
706 (setq dfs (lambda (mode &optional explored)
710 in (remove nil (cons (get mode
711 'derived-mode-parent)
712 (gethash mode yas--parents)))
714 unless (memq neighbour explored)
715 append (funcall dfs neighbour explored)))))
716 (remove-duplicates (append yas-extra-modes
717 (funcall dfs major-mode)))))
719 (defvar yas-minor-mode-hook nil
720 "Hook run when `yas-minor-mode' is turned on.")
723 (define-minor-mode yas-minor-mode
724 "Toggle YASnippet mode.
726 When YASnippet mode is enabled, `yas-expand', normally bound to
727 the TAB key, expands snippets of code depending on the major
730 With no argument, this command toggles the mode.
731 positive prefix argument turns on the mode.
732 Negative prefix argument turns off the mode.
735 \\{yas-minor-mode-map}"
737 ;; The indicator for the mode line.
740 (cond (yas-minor-mode
741 ;; Install the direct keymaps in `emulation-mode-map-alists'
742 ;; (we use `add-hook' even though it's not technically a hook,
743 ;; but it works). Then define variables named after modes to
744 ;; index `yas--direct-keymaps'.
746 ;; Also install the post-command-hook.
748 (add-hook 'emulation-mode-map-alists 'yas--direct-keymaps)
749 (add-hook 'post-command-hook 'yas--post-command-handler nil t)
750 ;; Set the `yas--direct-%s' vars for direct keymap expansion
752 (dolist (mode (yas--modes-to-activate))
753 (let ((name (intern (format "yas--direct-%s" mode))))
754 (set-default name nil)
755 (set (make-local-variable name) t)))
758 (yas--load-pending-jits))
760 ;; Uninstall the direct keymaps and the post-command hook
762 (remove-hook 'post-command-hook 'yas--post-command-handler t)
763 (remove-hook 'emulation-mode-map-alists 'yas--direct-keymaps))))
765 (defvar yas-dont-activate '(minibufferp)
766 "If non-nil don't let `yas-global-mode' affect some buffers.
768 If a function of zero arguments, then its result is used.
770 If a list of functions, then all functions must return nil to
771 activate yas for this buffer.
773 In Emacsen <= 23, this variable is buffer-local. Because
774 `yas-minor-mode-on' is called by `yas-global-mode' after
775 executing the buffer's major mode hook, setting this variable
776 there is an effective way to define exceptions to the \"global\"
777 activation behaviour.
779 In Emacsen > 23, only the global value is used. To define
780 per-mode exceptions to the \"global\" activation behaviour, call
781 `yas-minor-mode' with a negative argument directily in the major
783 (unless (> emacs-major-version 23)
785 (make-variable-buffer-local 'yas-dont-activate)))
788 (defun yas-minor-mode-on ()
789 "Turn on YASnippet minor mode.
791 Honour `yas-dont-activate', which see."
793 ;; Check `yas-dont-activate'
794 (unless (cond ((functionp yas-dont-activate)
795 (funcall yas-dont-activate))
796 ((consp yas-dont-activate)
797 (some #'funcall yas-dont-activate))
802 (define-globalized-minor-mode yas-global-mode yas-minor-mode yas-minor-mode-on
806 (defun yas--global-mode-reload-with-jit-maybe ()
807 "Run `yas-reload-all' when `yas-global-mode' is on."
808 (when yas-global-mode (yas-reload-all)))
810 (add-hook 'yas-global-mode-hook 'yas--global-mode-reload-with-jit-maybe)
815 (defvar yas--font-lock-keywords
816 (append '(("^#.*$" . font-lock-comment-face))
817 lisp-font-lock-keywords-2
819 (0 font-lock-keyword-face)
820 (1 font-lock-string-face t))
822 (0 font-lock-keyword-face)
823 (1 font-lock-warning-face t))
824 ("${" . font-lock-keyword-face)
825 ("$[0-9]+?" . font-lock-preprocessor-face)
826 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
828 (0 font-lock-keyword-face)))))
830 (defvar snippet-mode-map
831 (let ((map (make-sparse-keymap)))
832 (easy-menu-define nil
834 "Menu used when snippet-mode is active."
836 (mapcar #'(lambda (ent)
838 (define-key map (third ent) (second ent)))
839 (vector (first ent) (second ent) t))
840 '(("Load this snippet" yas-load-snippet-buffer "\C-c\C-l")
841 ("Load and quit window" yas-load-snippet-buffer-and-close "\C-c\C-c")
842 ("Try out this snippet" yas-tryout-snippet "\C-c\C-t")))))
844 "The keymap used when `snippet-mode' is active.")
847 (define-derived-mode snippet-mode text-mode "Snippet"
848 "A mode for editing yasnippets"
849 (setq font-lock-defaults '(yas--font-lock-keywords))
850 (set (make-local-variable 'require-final-newline) nil)
851 (set (make-local-variable 'comment-start) "#")
852 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
856 ;;; Internal structs for template management
858 (defstruct (yas--template (:constructor yas--make-blank-template))
859 "A template for a snippet."
869 group ;; as dictated by the #group: directive or .yas-make-groups
870 perm-group ;; as dictated by `yas-define-menu'
874 (defun yas--populate-template (template &rest args)
875 "Helper function to populate TEMPLATE with properties."
878 (position (intern (substring (symbol-name (car args)) 1))
879 (mapcar #'car (get 'yas--template 'cl-struct-slots)))
881 (setq args (cddr args)))
884 (defstruct (yas--table (:constructor yas--make-snippet-table (name)))
885 "A table to store snippets for a particular mode.
887 Has the following fields:
891 A symbol name normally corresponding to a major mode, but can
892 also be a pseudo major-mode to be referenced in
893 `yas-extra-modes', for example.
897 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
898 a string or a vector, where the former is the snippet's trigger
899 and the latter means it's a direct keybinding. NAMEHASH is yet
900 another hash of (NAME . TEMPLATE) where NAME is the snippet's
901 name and TEMPLATE is a `yas--template' object.
903 `yas--table-direct-keymap'
905 A keymap for the snippets in this table that have direct
906 keybindings. This is kept in sync with the keyhash, i.e., all
907 the elements of the keyhash that are vectors appear here as
908 bindings to `yas-expand-from-keymap'.
910 `yas--table-uuidhash'
912 A hash table mapping snippets uuid's to the same `yas--template'
913 objects. A snippet uuid defaults to the snippet's name."
915 (hash (make-hash-table :test 'equal))
916 (uuidhash (make-hash-table :test 'equal))
918 (direct-keymap (make-sparse-keymap)))
920 (defun yas--get-template-by-uuid (mode uuid)
921 "Find the snippet template in MODE by its UUID."
922 (let* ((table (gethash mode yas--tables mode)))
924 (gethash uuid (yas--table-uuidhash table)))))
926 ;; Apropos storing/updating in TABLE, this works in two steps:
928 ;; 1. `yas--remove-template-by-uuid' removes any
929 ;; keyhash-namehash-template mappings from TABLE, grabbing the
930 ;; snippet by its uuid. Also removes mappings from TABLE's
931 ;; `yas--table-direct-keymap' (FIXME: and should probably take care
932 ;; of potentially stale menu bindings right?.)
934 ;; 2. `yas--add-template' adds this all over again.
936 ;; Create a new or add to an existing keyhash-namehash mapping.
938 ;; For reference on understanding this, consider three snippet
941 ;; A: # name: The Foo
943 ;; # binding: C-c M-l
945 ;; B: # name: Mrs Foo
948 ;; C: # name: The Bar
949 ;; # binding: C-c M-l
954 ;; keyhash namehashes(3) yas--template structs(4)
955 ;; -----------------------------------------------------
958 ;; "foo" ---> "The Foo" ---> [yas--template A] |
959 ;; "Mrs Foo" ---> [yas--template B] |
961 ;; [C-c M-l] ---> "The Foo" -------------------------/
962 ;; "The Bar" ---> [yas--template C]
964 ;; "baz" ---> "Baz" ---> [yas--template D]
966 ;; Additionally, since uuid defaults to the name, we have a
967 ;; `yas--table-uuidhash' for TABLE
969 ;; uuidhash yas--template structs
970 ;; -------------------------------
971 ;; "The Foo" ---> [yas--template A]
972 ;; "Mrs Foo" ---> [yas--template B]
973 ;; "The Bar" ---> [yas--template C]
974 ;; "Baz" ---> [yas--template D]
976 ;; FIXME: the more I look at this data-structure the more I think I'm
977 ;; stupid. There has to be an easier way (but beware lots of code
980 (defun yas--remove-template-by-uuid (table uuid)
981 "Remove from TABLE a template identified by UUID."
982 (let ((template (gethash uuid (yas--table-uuidhash table))))
984 (let* ((name (yas--template-name template))
986 ;; Remove the name from each of the targeted namehashes
988 (maphash #'(lambda (k v)
989 (let ((template (gethash name v)))
991 (eq uuid (yas--template-uuid template)))
993 (when (zerop (hash-table-count v))
994 (push k empty-keys)))))
995 (yas--table-hash table))
996 ;; Remove the namehash themselves if they've become empty
998 (dolist (key empty-keys)
1000 (define-key (yas--table-direct-keymap table) key nil))
1001 (remhash key (yas--table-hash table)))
1003 ;; Finally, remove the uuid from the uuidhash
1005 (remhash uuid (yas--table-uuidhash table))))))
1007 (defun yas--add-template (table template)
1008 "Store in TABLE the snippet template TEMPLATE.
1010 KEY can be a string (trigger key) of a vector (direct
1012 (let ((name (yas--template-name template))
1013 (key (yas--template-key template))
1014 (keybinding (yas--template-keybinding template))
1015 (_menu-binding-pair (yas--template-menu-binding-pair-get-create template)))
1016 (dolist (k (remove nil (list key keybinding)))
1020 (yas--table-hash table))
1022 (make-hash-table :test 'equal)
1023 (yas--table-hash table))))
1025 (define-key (yas--table-direct-keymap table) k 'yas-expand-from-keymap)))
1027 ;; Update TABLE's `yas--table-uuidhash'
1028 (puthash (yas--template-uuid template)
1030 (yas--table-uuidhash table))))
1032 (defun yas--update-template (table template)
1033 "Add or update TEMPLATE in TABLE.
1035 Also takes care of adding and updating to the associated menu."
1036 ;; Remove from table by uuid
1038 (yas--remove-template-by-uuid table (yas--template-uuid template))
1039 ;; Add to table again
1041 (yas--add-template table template)
1042 ;; Take care of the menu
1045 (yas--update-template-menu table template)))
1047 (defun yas--update-template-menu (table template)
1048 "Update every menu-related for TEMPLATE."
1049 (let ((menu-binding-pair (yas--template-menu-binding-pair-get-create template))
1050 (key (yas--template-key template))
1051 (keybinding (yas--template-keybinding template)))
1052 ;; The snippet might have changed name or keys, so update
1053 ;; user-visible strings
1055 (unless (eq (cdr menu-binding-pair) :none)
1056 ;; the menu item name
1058 (setf (cadar menu-binding-pair) (yas--template-name template))
1059 ;; the :keys information (also visible to the user)
1060 (setf (getf (cdr (car menu-binding-pair)) :keys)
1061 (or (and keybinding (key-description keybinding))
1062 (and key (concat key yas-trigger-symbol))))))
1063 (unless (yas--template-menu-managed-by-yas-define-menu template)
1065 (yas--menu-keymap-get-create (yas--table-mode table)
1066 (mapcar #'yas--table-mode
1067 (yas--table-parents table))))
1068 (group (yas--template-group template)))
1069 ;; Remove from menu keymap
1071 (assert menu-keymap)
1072 (yas--delete-from-keymap menu-keymap (yas--template-uuid template))
1074 ;; Add necessary subgroups as necessary.
1076 (dolist (subgroup group)
1077 (let ((subgroup-keymap (lookup-key menu-keymap (vector (make-symbol subgroup)))))
1078 (unless (and subgroup-keymap
1079 (keymapp subgroup-keymap))
1080 (setq subgroup-keymap (make-sparse-keymap))
1081 (define-key menu-keymap (vector (make-symbol subgroup))
1082 `(menu-item ,subgroup ,subgroup-keymap)))
1083 (setq menu-keymap subgroup-keymap)))
1085 ;; Add this entry to the keymap
1087 (define-key menu-keymap
1088 (vector (make-symbol (yas--template-uuid template)))
1089 (car (yas--template-menu-binding-pair template))))))
1091 (defun yas--namehash-templates-alist (namehash)
1092 "Return NAMEHASH as an alist."
1094 (maphash #'(lambda (k v)
1095 (push (cons k v) alist))
1099 (defun yas--fetch (table key)
1100 "Fetch templates in TABLE by KEY.
1102 Return a list of cons (NAME . TEMPLATE) where NAME is a
1103 string and TEMPLATE is a `yas--template' structure."
1104 (let* ((keyhash (yas--table-hash table))
1105 (namehash (and keyhash (gethash key keyhash))))
1107 (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash)))))
1110 ;;; Filtering/condition logic
1112 (defun yas--eval-condition (condition)
1119 (yas--message 1 "Error in condition evaluation: %s" (error-message-string err))
1123 (defun yas--filter-templates-by-condition (templates)
1124 "Filter the templates using the applicable condition.
1126 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1127 string and TEMPLATE is a `yas--template' structure.
1129 This function implements the rules described in
1130 `yas-buffer-local-condition'. See that variables documentation."
1131 (let ((requirement (yas--require-template-specific-condition-p)))
1132 (if (eq requirement 'always)
1134 (remove-if-not #'(lambda (pair)
1135 (yas--template-can-expand-p
1136 (yas--template-condition (cdr pair)) requirement))
1139 (defun yas--require-template-specific-condition-p ()
1140 "Decide if this buffer requests/requires snippet-specific
1141 conditions to filter out potential expansions."
1142 (if (eq 'always yas-buffer-local-condition)
1144 (let ((local-condition (or (and (consp yas-buffer-local-condition)
1145 (yas--eval-condition yas-buffer-local-condition))
1146 yas-buffer-local-condition)))
1147 (when local-condition
1148 (if (eq local-condition t)
1150 (and (consp local-condition)
1151 (eq 'require-snippet-condition (car local-condition))
1152 (symbolp (cdr local-condition))
1153 (cdr local-condition)))))))
1155 (defun yas--template-can-expand-p (condition requirement)
1156 "Evaluate CONDITION and REQUIREMENT and return a boolean."
1157 (let* ((result (or (null condition)
1158 (yas--eval-condition condition))))
1159 (cond ((eq requirement t)
1162 (eq requirement result)))))
1164 (defun yas--table-templates (table)
1167 (maphash #'(lambda (_key namehash)
1168 (maphash #'(lambda (name template)
1169 (push (cons name template) acc))
1171 (yas--table-hash table))
1172 (yas--filter-templates-by-condition acc))))
1174 (defun yas--current-key ()
1175 "Get the key under current position.
1176 A key is used to find the template of a snippet in the current snippet-table."
1177 (let ((start (point))
1179 (syntaxes yas-key-syntaxes)
1183 (while (and (not done) syntaxes)
1184 (setq syntax (car syntaxes))
1185 (setq syntaxes (cdr syntaxes))
1187 (skip-syntax-backward syntax)
1188 (setq start (point)))
1190 (mapcan #'(lambda (table)
1191 (yas--fetch table (buffer-substring-no-properties start end)))
1192 (yas--get-snippet-tables)))
1201 (defun yas--table-all-keys (table)
1202 "Get trigger keys of all active snippets in TABLE."
1204 (maphash #'(lambda (key namehash)
1205 (when (yas--filter-templates-by-condition (yas--namehash-templates-alist namehash))
1207 (yas--table-hash table))
1210 (defun yas--table-mode (table)
1211 (intern (yas--table-name table)))
1214 ;;; Internal functions and macros:
1216 (defun yas--real-mode? (mode)
1217 "Try to find out if MODE is a real mode.
1219 The MODE bound to a function (like `c-mode') is considered real
1220 mode. Other well known mode like `ruby-mode' which is not part of
1221 Emacs might not bound to a function until it is loaded. So
1222 yasnippet keeps a list of modes like this to help the judgment."
1224 (find mode yas--known-modes)))
1226 (defun yas--eval-lisp (form)
1227 "Evaluate FORM and convert the result to string."
1228 (let ((retval (catch 'yas--exception
1234 (let ((result (eval form)))
1236 (format "%s" result))))))
1237 (error (if yas-good-grace
1238 (yas--format "elisp error! %s" (error-message-string err))
1239 (error (yas--format "elisp error: %s"
1240 (error-message-string err)))))))))
1241 (when (and (consp retval)
1242 (eq 'yas--exception (car retval)))
1243 (error (cdr retval)))
1246 (defun yas--eval-lisp-no-saves (form)
1249 (error (if yas-good-grace
1250 (yas--format "elisp error! %s" (error-message-string err))
1251 (error (yas--format "elisp error: %s"
1252 (error-message-string err)))))))
1254 (defun yas--read-lisp (string &optional nil-on-error)
1255 "Read STRING as a elisp expression and return it.
1257 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1258 return an expression that when evaluated will issue an error."
1261 (error (and (not nil-on-error)
1262 `(error (error-message-string ,err))))))
1264 (defun yas--read-keybinding (keybinding)
1265 "Read KEYBINDING as a snippet keybinding, return a vector."
1266 (when (and keybinding
1267 (not (string-match "keybinding" keybinding)))
1269 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1271 (read-kbd-macro keybinding 'need-vector))))
1274 (yas--message 3 "warning: keybinding \"%s\" invalid since %s."
1275 keybinding (error-message-string err))
1278 (defun yas--table-get-create (mode)
1279 "Get or create the snippet table corresponding to MODE."
1280 (let ((table (gethash mode
1283 (setq table (yas--make-snippet-table (symbol-name mode)))
1284 (puthash mode table yas--tables)
1285 (push (cons (intern (format "yas--direct-%s" mode))
1286 (yas--table-direct-keymap table))
1287 yas--direct-keymaps))
1290 (defun yas--get-snippet-tables ()
1291 "Get snippet tables for current buffer.
1293 Return a list of `yas--table' objects. The list of modes to
1294 consider is returned by `yas--modes-to-activate'"
1296 (mapcar #'(lambda (name)
1297 (gethash name yas--tables))
1298 (yas--modes-to-activate))))
1300 (defun yas--menu-keymap-get-create (mode &optional parents)
1301 "Get or create the menu keymap for MODE and its PARENTS.
1303 This may very well create a plethora of menu keymaps and arrange
1304 them all in `yas--menu-table'"
1305 (let* ((menu-keymap (or (gethash mode yas--menu-table)
1306 (puthash mode (make-sparse-keymap) yas--menu-table))))
1307 (mapc #'yas--menu-keymap-get-create parents)
1308 (define-key yas--minor-mode-menu (vector mode)
1309 `(menu-item ,(symbol-name mode) ,menu-keymap
1310 :visible (yas--show-menu-p ',mode)))
1314 (defmacro yas--called-interactively-p (&optional kind)
1315 "A backward-compatible version of `called-interactively-p'.
1317 Optional KIND is as documented at `called-interactively-p'
1318 in GNU Emacs 24.1 or higher."
1319 (if (string< emacs-version "24.1")
1320 '(called-interactively-p)
1321 `(called-interactively-p ,kind)))
1324 ;;; Template-related and snippet loading functions
1326 (defun yas--parse-template (&optional file)
1327 "Parse the template in the current buffer.
1329 Optional FILE is the absolute file name of the file being
1332 Optional GROUP is the group where the template is to go,
1333 otherwise we attempt to calculate it from FILE.
1335 Return a snippet-definition, i.e. a list
1337 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1339 If the buffer contains a line of \"# --\" then the contents above
1340 this line are ignored. Directives can set most of these with the syntax:
1342 # directive-name : directive-value
1344 Here's a list of currently recognized directives:
1355 (goto-char (point-min))
1356 (let* ((type 'snippet)
1358 (file-name-nondirectory file)))
1364 (yas--calculate-group file)))
1368 (if (re-search-forward "^# --\n" nil t)
1369 (progn (setq template
1370 (buffer-substring-no-properties (point)
1372 (setq bound (point))
1373 (goto-char (point-min))
1374 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1375 (when (string= "uuid" (match-string-no-properties 1))
1376 (setq uuid (match-string-no-properties 2)))
1377 (when (string= "type" (match-string-no-properties 1))
1378 (setq type (if (string= "command" (match-string-no-properties 2))
1381 (when (string= "key" (match-string-no-properties 1))
1382 (setq key (match-string-no-properties 2)))
1383 (when (string= "name" (match-string-no-properties 1))
1384 (setq name (match-string-no-properties 2)))
1385 (when (string= "condition" (match-string-no-properties 1))
1386 (setq condition (yas--read-lisp (match-string-no-properties 2))))
1387 (when (string= "group" (match-string-no-properties 1))
1388 (setq group (match-string-no-properties 2)))
1389 (when (string= "expand-env" (match-string-no-properties 1))
1390 (setq expand-env (yas--read-lisp (match-string-no-properties 2)
1392 (when (string= "binding" (match-string-no-properties 1))
1393 (setq binding (match-string-no-properties 2)))))
1395 (buffer-substring-no-properties (point-min) (point-max))))
1396 (unless (or key binding)
1397 (setq key (and file (file-name-nondirectory file))))
1398 (when (eq type 'command)
1399 (setq template (yas--read-lisp (concat "(progn" template ")"))))
1401 (setq group (split-string group "\\.")))
1402 (list key template name condition group expand-env file binding uuid)))
1404 (defun yas--calculate-group (file)
1405 "Calculate the group for snippet file path FILE."
1406 (let* ((dominating-dir (locate-dominating-file file
1407 ".yas-make-groups"))
1408 (extra-path (and dominating-dir
1409 (replace-regexp-in-string (concat "^"
1410 (expand-file-name dominating-dir))
1412 (expand-file-name file))))
1413 (extra-dir (and extra-path
1414 (file-name-directory extra-path)))
1415 (group (and extra-dir
1416 (replace-regexp-in-string "/"
1418 (directory-file-name extra-dir)))))
1421 (defun yas--subdirs (directory &optional filep)
1422 "Return subdirs or files of DIRECTORY according to FILEP."
1423 (remove-if (lambda (file)
1424 (or (string-match "^\\."
1425 (file-name-nondirectory file))
1426 (string-match "^#.*#$"
1427 (file-name-nondirectory file))
1429 (file-name-nondirectory file))
1431 (file-directory-p file)
1432 (not (file-directory-p file)))))
1433 (directory-files directory t)))
1435 (defun yas--make-menu-binding (template)
1436 (let ((mode (yas--table-mode (yas--template-table template))))
1437 `(lambda () (interactive) (yas--expand-or-visit-from-menu ',mode ,(yas--template-uuid template)))))
1439 (defun yas--expand-or-visit-from-menu (mode uuid)
1440 (let* ((table (yas--table-get-create mode))
1441 (yas--current-template (and table
1442 (gethash uuid (yas--table-uuidhash table)))))
1443 (when yas--current-template
1444 (if yas-visit-from-menu
1445 (yas--visit-snippet-file-1 yas--current-template)
1446 (let ((where (if (region-active-p)
1447 (cons (region-beginning) (region-end))
1448 (cons (point) (point)))))
1449 (yas-expand-snippet (yas--template-content yas--current-template)
1452 (yas--template-expand-env yas--current-template)))))))
1454 (defun yas--key-from-desc (text)
1455 "Return a yasnippet key from a description string TEXT."
1456 (replace-regexp-in-string "\\(\\w+\\).*" "\\1" text))
1459 ;;; Popping up for keys and templates
1461 (defvar yas--x-pretty-prompt-templates nil
1462 "If non-nil, attempt to prompt for templates like TextMate.")
1465 (defun yas--prompt-for-template (templates &optional prompt)
1466 "Interactively choose a template from the list TEMPLATES.
1468 TEMPLATES is a list of `yas--template'.
1470 Optional PROMPT sets the prompt to use."
1473 (sort templates #'(lambda (t1 t2)
1474 (< (length (yas--template-name t1))
1475 (length (yas--template-name t2))))))
1476 (if yas--x-pretty-prompt-templates
1477 (yas--x-pretty-prompt-templates "Choose a snippet" templates)
1478 (some #'(lambda (fn)
1479 (funcall fn (or prompt "Choose a snippet: ")
1481 #'yas--template-name))
1482 yas-prompt-functions))))
1484 (defun yas--prompt-for-keys (keys &optional prompt)
1485 "Interactively choose a template key from the list KEYS.
1487 Optional PROMPT sets the prompt to use."
1489 (some #'(lambda (fn)
1490 (funcall fn (or prompt "Choose a snippet key: ") keys))
1491 yas-prompt-functions)))
1493 (defun yas--prompt-for-table (tables &optional prompt)
1494 "Interactively choose a table from the list TABLES.
1496 Optional PROMPT sets the prompt to use."
1498 (some #'(lambda (fn)
1499 (funcall fn (or prompt "Choose a snippet table: ")
1502 yas-prompt-functions)))
1504 (defun yas-x-prompt (prompt choices &optional display-fn)
1505 "Display choices in a x-window prompt."
1506 ;; FIXME: HACK: if we notice that one of the objects in choices is
1507 ;; actually a `yas--template', defer to `yas--x-prompt-pretty-templates'
1509 ;; This would be better implemented by passing CHOICES as a
1510 ;; structured tree rather than a list. Modifications would go as far
1511 ;; up as `yas--all-templates' I think.
1513 (when (and window-system choices)
1515 (let (menu d) ;; d for display
1517 (setq d (or (and display-fn (funcall display-fn c))
1520 (push (cons (concat " " d) c) menu))
1522 (push (car d) menu))))
1523 (setq menu (list prompt (push "title" menu)))
1524 (x-popup-menu (if (fboundp 'posn-at-point)
1525 (let ((x-y (posn-x-y (posn-at-point (point)))))
1526 (list (list (+ (car x-y) 10)
1534 (defun yas--x-pretty-prompt-templates (prompt templates)
1535 "Display TEMPLATES, grouping neatly by table name."
1536 (let ((organized (make-hash-table :test #'equal))
1540 (dolist (tl templates)
1541 (puthash (yas--template-table tl)
1543 (gethash (yas--template-table tl) organized))
1545 (setq more-than-one-table (> (hash-table-count organized) 1))
1546 (setq prefix (if more-than-one-table
1548 (if more-than-one-table
1549 (maphash #'(lambda (table templates)
1550 (push (yas--table-name table) menu)
1551 (dolist (tl templates)
1552 (push (cons (concat prefix (yas--template-name tl)) tl) menu))) organized)
1553 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas--template-name tl)) tl)) templates)))
1555 (setq menu (nreverse menu))
1556 (or (x-popup-menu (if (fboundp 'posn-at-point)
1557 (let ((x-y (posn-x-y (posn-at-point (point)))))
1558 (list (list (+ (car x-y) 10)
1562 (list prompt (push "title" menu)))
1565 (defun yas-ido-prompt (prompt choices &optional display-fn)
1566 (when (and (fboundp 'ido-completing-read)
1567 (or (>= emacs-major-version 24)
1569 (yas-completing-prompt prompt choices display-fn #'ido-completing-read)))
1571 (defun yas-dropdown-prompt (_prompt choices &optional display-fn)
1572 (when (fboundp 'dropdown-list)
1573 (let (formatted-choices
1577 (dolist (choice choices)
1578 (setq d (or (and display-fn (funcall display-fn choice))
1581 (push d formatted-choices)
1582 (push choice filtered-choices)))
1584 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1586 (nth n filtered-choices)
1589 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1590 (let (formatted-choices
1594 (completion-fn (or completion-fn
1595 #'completing-read)))
1596 (dolist (choice choices)
1597 (setq d (or (and display-fn (funcall display-fn choice))
1600 (push d formatted-choices)
1601 (push choice filtered-choices)))
1602 (setq chosen (and formatted-choices
1603 (funcall completion-fn prompt
1609 (let ((position (or (and chosen
1610 (position chosen formatted-choices :test #'string=))
1612 (nth position filtered-choices))))
1614 (defun yas-no-prompt (_prompt choices &optional _display-fn)
1618 ;;; Defining snippets
1619 ;; This consists of creating and registering `yas--template' objects in the
1623 (defvar yas--creating-compiled-snippets nil)
1625 (defun yas--define-snippets-1 (snippet snippet-table)
1626 "Helper for `yas-define-snippets'."
1627 ;; X) Calculate some more defaults on the values returned by
1628 ;; `yas--parse-template'.
1630 (let* ((file (seventh snippet))
1632 (name (or (third snippet)
1634 (file-name-directory file))))
1635 (condition (fourth snippet))
1636 (group (fifth snippet))
1637 (keybinding (yas--read-keybinding (eighth snippet)))
1638 (uuid (or (ninth snippet)
1640 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1641 (yas--make-blank-template))))
1642 ;; X) populate the template object
1644 (yas--populate-template template
1645 :table snippet-table
1647 :content (second snippet)
1650 :condition condition
1651 :expand-env (sixth snippet)
1652 :file (seventh snippet)
1653 :keybinding keybinding
1655 ;; X) Update this template in the appropriate table. This step
1656 ;; also will take care of adding the key indicators in the
1657 ;; templates menu entry, if any
1659 (yas--update-template snippet-table template)
1660 ;; X) Return the template
1665 (defun yas-define-snippets (mode snippets)
1666 "Define SNIPPETS for MODE.
1668 SNIPPETS is a list of snippet definitions, each taking the
1671 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1673 Within these, only KEY and TEMPLATE are actually mandatory.
1675 TEMPLATE might be a Lisp form or a string, depending on whether
1676 this is a snippet or a snippet-command.
1678 CONDITION, EXPAND-ENV and KEYBINDING are Lisp forms, they have
1679 been `yas--read-lisp'-ed and will eventually be
1680 `yas--eval-lisp'-ed.
1682 The remaining elements are strings.
1684 FILE is probably of very little use if you're programatically
1687 UUID is the snippets \"unique-id\". Loading a second snippet file
1688 with the same uuid replaced the previous snippet.
1690 You can use `yas--parse-template' to return such lists based on
1691 the current buffers contents."
1692 (if yas--creating-compiled-snippets
1694 (insert ";;; Snippet definitions:\n;;;\n")
1695 (let ((literal-snippets (list))
1697 (dolist (snippet snippets)
1698 (let ((key (nth 0 snippet))
1699 (template-content (nth 1 snippet))
1700 (name (nth 2 snippet))
1701 (condition (nth 3 snippet))
1702 (group (nth 4 snippet))
1703 (expand-env (nth 5 snippet))
1704 (file nil) ;; omit on purpose
1705 (binding (nth 7 snippet))
1706 (uuid (nth 8 snippet)))
1717 (insert (pp-to-string
1718 `(yas-define-snippets ',mode ',literal-snippets)))
1721 (let ((snippet-table (yas--table-get-create mode))
1723 (dolist (snippet snippets)
1724 (setq template (yas--define-snippets-1 snippet
1729 ;;; Loading snippets from files
1731 (defun yas--load-yas-setup-file (file)
1732 (if (not yas--creating-compiled-snippets)
1734 (load file 'noerror)
1735 (let ((elfile (concat file ".el")))
1736 (when (file-exists-p elfile)
1737 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1738 (insert-file-contents elfile)
1739 (goto-char (point-max))))))
1741 (defun yas--define-parents (mode parents)
1742 "Add PARENTS to the list of MODE's parents."
1743 (puthash mode (remove-duplicates
1745 (gethash mode yas--parents)))
1748 (defun yas-load-directory (top-level-dir &optional use-jit interactive)
1749 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1751 Below TOP-LEVEL-DIR each directory should be a mode name.
1753 Optional USE-JIT use jit-loading of snippets."
1754 (interactive "DSelect the root directory: ni\np")
1755 (unless yas-snippet-dirs
1756 (setq yas-snippet-dirs top-level-dir))
1757 (dolist (dir (yas--subdirs top-level-dir))
1758 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1759 (concat dir "/dummy")))
1760 (mode-sym (car major-mode-and-parents))
1761 (parents (cdr major-mode-and-parents)))
1762 ;; Attention: The parents and the menus are already defined
1763 ;; here, even if the snippets are later jit-loaded.
1765 ;; * We need to know the parents at this point since entering a
1766 ;; given mode should jit load for its parents
1767 ;; immediately. This could be reviewed, the parents could be
1768 ;; discovered just-in-time-as well
1770 ;; * We need to create the menus here to support the `full'
1771 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1773 (yas--define-parents mode-sym parents)
1774 (yas--menu-keymap-get-create mode-sym)
1775 (let ((fun `(lambda () ;; FIXME: Simulating lexical-binding.
1776 (yas--load-directory-1 ',dir ',mode-sym))))
1778 (not (some #'(lambda (buffer)
1779 (with-current-buffer buffer
1780 ;; FIXME: Shouldn't this use derived-mode-p?
1781 (when (eq major-mode mode-sym)
1782 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1785 (yas--schedule-jit mode-sym fun)
1788 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1790 (defun yas--load-directory-1 (directory mode-sym)
1791 "Recursively load snippet templates from DIRECTORY."
1792 (if yas--creating-compiled-snippets
1793 (let ((output-file (expand-file-name ".yas-compiled-snippets.el"
1795 (with-temp-file output-file
1796 (insert (format ";;; Compiled snippets and support files for `%s'\n"
1798 (yas--load-directory-2 directory mode-sym)
1799 (insert (format ";;; Do not edit! File generated at %s\n"
1800 (current-time-string)))))
1802 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1803 (if (and (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1804 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1805 (yas--message 2 "Loading snippet files from %s" directory)
1806 (yas--load-directory-2 directory mode-sym)))))
1808 (defun yas--load-directory-2 (directory mode-sym)
1809 ;; Load .yas-setup.el files wherever we find them
1811 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1812 (let* ((default-directory directory)
1814 ;; load the snippet files
1817 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1818 (when (file-readable-p file)
1819 (insert-file-contents file nil nil nil t)
1820 (push (yas--parse-template file)
1823 (yas-define-snippets mode-sym
1825 ;; now recurse to a lower level
1827 (dolist (subdir (yas--subdirs directory))
1828 (yas--load-directory-2 subdir
1831 (defun yas--load-snippet-dirs (&optional nojit)
1832 "Reload the directories listed in `yas-snippet-dirs' or
1833 prompt the user to select one."
1835 (if yas-snippet-dirs
1836 (dolist (directory (reverse (yas-snippet-dirs)))
1837 (cond ((file-directory-p directory)
1838 (yas-load-directory directory (not nojit))
1840 (yas--message 3 "Loaded %s" directory)
1841 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1843 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1844 (call-interactively 'yas-load-directory))
1847 (defun yas-reload-all (&optional interactive)
1848 "Reload all snippets and rebuild the YASnippet menu.
1850 When called interactively force immediate reload of all known
1851 snippets under `yas-snippet-dirs', otherwise use just-in-time
1856 (snippet-editing-buffers
1857 (remove-if-not #'(lambda (buffer)
1858 (with-current-buffer buffer yas--editing-template))
1860 ;; Warn if there are buffers visiting snippets, since reloading will break
1861 ;; any on-line editing of those buffers.
1863 (when snippet-editing-buffers
1865 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1866 (mapc #'kill-buffer snippet-editing-buffers)
1867 (yas--message 1 "Aborted reload...")
1869 ;; in a non-interactive use, at least set
1870 ;; `yas--editing-template' to nil, make it guess it next time around
1871 (mapc #'(lambda (buffer)
1872 (with-current-buffer buffer
1873 (kill-local-variable 'yas--editing-template)))
1876 ;; Empty all snippet tables and parenting info
1878 (setq yas--tables (make-hash-table))
1879 (setq yas--parents (make-hash-table))
1881 ;; Before killing `yas--menu-table' use its keys to cleanup the
1882 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1883 ;; up `yas-minor-mode-map', which points to it)
1885 (maphash #'(lambda (menu-symbol _keymap)
1886 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1888 ;; Now empty `yas--menu-table' as well
1889 (setq yas--menu-table (make-hash-table))
1891 ;; Cancel all pending 'yas--scheduled-jit-loads'
1893 (setq yas--scheduled-jit-loads (make-hash-table))
1895 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1896 ;; the user to select one.
1898 (setq errors (yas--load-snippet-dirs interactive))
1899 ;; Reload the direct keybindings
1901 (yas-direct-keymaps-reload)
1903 (yas--message 3 "Reloaded everything%s...%s."
1904 (if interactive "" " (snippets will load just-in-time)")
1905 (if errors " (some errors, check *Messages*)" "")))))
1907 (defun yas--load-pending-jits ()
1908 (dolist (mode (yas--modes-to-activate))
1909 (let ((funs (reverse (gethash mode yas--scheduled-jit-loads))))
1910 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1912 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode fun)
1914 (remhash mode yas--scheduled-jit-loads))))
1916 ;; (when (<= emacs-major-version 22)
1917 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1919 (defun yas--quote-string (string)
1920 "Escape and quote STRING.
1921 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1923 (replace-regexp-in-string "[\\\"]"
1929 ;;; Snippet compilation function
1931 (defun yas--initialize ()
1932 "For backward compatibility, enable `yas-minor-mode' globally."
1933 (yas-global-mode 1))
1935 (defun yas-compile-directory (top-level-dir)
1936 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1938 This works by stubbing a few functions, then calling
1939 `yas-load-directory'."
1940 (interactive "DTop level snippet directory?")
1941 (let ((yas--creating-compiled-snippets t))
1942 (yas-load-directory top-level-dir nil)))
1944 (defun yas-recompile-all ()
1945 "Compile every dir in `yas-snippet-dirs'."
1947 (mapc #'yas-compile-directory (yas-snippet-dirs)))
1953 (defvar yas--scheduled-jit-loads (make-hash-table)
1954 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
1956 (defun yas--schedule-jit (mode fun)
1957 (push fun (gethash mode yas--scheduled-jit-loads)))
1961 ;;; Some user level functions
1965 (message (concat "yasnippet (version "
1967 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1970 ;;; Apropos snippet menu:
1972 ;; The snippet menu keymaps are store by mode in hash table called
1973 ;; `yas--menu-table'. They are linked to the main menu in
1974 ;; `yas--menu-keymap-get-create' and are initially created empty,
1975 ;; reflecting the table hierarchy.
1977 ;; They can be populated in two mutually exclusive ways: (1) by
1978 ;; reading `yas--template-group', which in turn is populated by the "#
1979 ;; group:" directives of the snippets or the ".yas-make-groups" file
1980 ;; or (2) by using a separate `yas-define-menu' call, which declares a
1981 ;; menu structure based on snippets uuids.
1983 ;; Both situations are handled in `yas--update-template-menu', which
1984 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
1985 ;; that can tell between the two situations.
1989 ;; * if `yas-define-menu' is used it must run before
1990 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
1991 ;; duplicate entries. The `yas--template' objects are created in
1992 ;; `yas-define-menu', holding nothing but the menu entry,
1993 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
1994 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
1995 ;; part is then stored in the menu keymap itself which make the item
1996 ;; appear to the user. These limitations could probably be revised.
1998 ;; * The `yas--template-perm-group' slot is only used in
1999 ;; `yas-describe-tables'.
2001 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2002 "Get TEMPLATE's menu binding or assign it a new one.
2004 TYPE may be `:stay', signaling this menu binding should be
2005 static in the menu."
2006 (or (yas--template-menu-binding-pair template)
2007 (let (;; (key (yas--template-key template))
2008 ;; (keybinding (yas--template-keybinding template))
2010 (setf (yas--template-menu-binding-pair template)
2011 (cons `(menu-item ,(or (yas--template-name template)
2012 (yas--template-uuid template))
2013 ,(yas--make-menu-binding template)
2016 (defun yas--template-menu-managed-by-yas-define-menu (template)
2017 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2018 (cdr (yas--template-menu-binding-pair template)))
2021 (defun yas--show-menu-p (mode)
2022 (cond ((eq yas-use-menu 'abbreviate)
2024 (mapcar #'(lambda (table)
2025 (yas--table-mode table))
2026 (yas--get-snippet-tables))))
2027 ((eq yas-use-menu 'full)
2029 ((eq yas-use-menu t)
2032 (defun yas--delete-from-keymap (keymap uuid)
2033 "Recursively delete items with UUID from KEYMAP and its submenus."
2035 ;; XXX: This used to skip any submenus named \"parent mode\"
2037 ;; First of all, recursively enter submenus, i.e. the tree is
2038 ;; searched depth first so that stale submenus can be found in the
2041 (mapc #'(lambda (item)
2042 (when (and (listp (cdr item))
2043 (keymapp (third (cdr item))))
2044 (yas--delete-from-keymap (third (cdr item)) uuid)))
2046 ;; Set the uuid entry to nil
2048 (define-key keymap (vector (make-symbol uuid)) nil)
2049 ;; Destructively modify keymap
2051 (setcdr keymap (delete-if #'(lambda (item)
2052 (or (null (cdr item))
2053 (and (keymapp (third (cdr item)))
2054 (null (cdr (third (cdr item)))))))
2057 (defun yas-define-menu (mode menu &optional omit-items)
2058 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2060 MENU is a list, its elements can be:
2062 - (yas-item UUID) : Creates an entry the snippet identified with
2063 UUID. The menu entry for a snippet thus identified is
2064 permanent, i.e. it will never move (be reordered) in the menu.
2066 - (yas-separator) : Creates a separator
2068 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2069 SUBMENU has the same form as MENU. NAME is also added to the
2070 list of groups of the snippets defined thereafter.
2072 OMIT-ITEMS is a list of snippet uuid's that will always be
2073 omitted from MODE's menu, even if they're manually loaded.
2075 This function does nothing if `yas-use-menu' is nil."
2077 (let* ((table (yas--table-get-create mode))
2078 (hash (yas--table-uuidhash table)))
2079 (yas--define-menu-1 table
2080 (yas--menu-keymap-get-create mode)
2083 (dolist (uuid omit-items)
2084 (let ((template (or (gethash uuid hash)
2085 (yas--populate-template (puthash uuid
2086 (yas--make-blank-template)
2090 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2092 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2093 "Helper for `yas-define-menu'."
2094 (dolist (e (reverse menu))
2095 (cond ((eq (first e) 'yas-item)
2096 (let ((template (or (gethash (second e) uuidhash)
2097 (yas--populate-template (puthash (second e)
2098 (yas--make-blank-template)
2101 :perm-group group-list
2102 :uuid (second e)))))
2103 (define-key menu-keymap (vector (gensym))
2104 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2105 ((eq (first e) 'yas-submenu)
2106 (let ((subkeymap (make-sparse-keymap)))
2107 (define-key menu-keymap (vector (gensym))
2108 `(menu-item ,(second e) ,subkeymap))
2109 (yas--define-menu-1 table
2113 (append group-list (list (second e))))))
2114 ((eq (first e) 'yas-separator)
2115 (define-key menu-keymap (vector (gensym))
2116 '(menu-item "----")))
2118 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2120 (defun yas--define (mode key template &optional name condition group)
2121 "Define a snippet. Expanding KEY into TEMPLATE.
2123 NAME is a description to this template. Also update the menu if
2124 `yas-use-menu' is t. CONDITION is the condition attached to
2125 this snippet. If you attach a condition to a snippet, then it
2126 will only be expanded when the condition evaluated to non-nil."
2127 (yas-define-snippets mode
2128 (list (list key template name condition group))))
2130 (defun yas-hippie-try-expand (first-time?)
2131 "Integrate with hippie expand.
2133 Just put this function in `hippie-expand-try-functions-list'."
2134 (when yas-minor-mode
2135 (if (not first-time?)
2136 (let ((yas-fallback-behavior 'return-nil))
2142 ;;; Apropos condition-cache:
2147 (defvar yas--condition-cache-timestamp nil)
2148 (defmacro yas-define-condition-cache (func doc &rest body)
2149 "Define a function FUNC with doc DOC and body BODY.
2150 BODY is executed at most once every snippet expansion attempt, to check
2151 expansion conditions.
2153 It doesn't make any sense to call FUNC programatically."
2154 `(defun ,func () ,(if (and doc
2157 "\n\nFor use in snippets' conditions. Within each
2158 snippet-expansion routine like `yas-expand', computes actual
2159 value for the first time then always returns a cached value.")
2160 (setq body (cons doc body))
2162 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2163 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2164 (cdr timestamp-and-value)
2165 (let ((new-value (progn
2168 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2171 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2172 (defun yas-expand-from-trigger-key (&optional field)
2173 "Expand a snippet before point.
2175 If no snippet expansion is possible, fall back to the behaviour
2176 defined in `yas-fallback-behavior'.
2178 Optional argument FIELD is for non-interactive use and is an
2179 object satisfying `yas--field-p' to restrict the expansion to."
2181 (setq yas--condition-cache-timestamp (current-time))
2182 (let (templates-and-pos)
2183 (unless (and yas-expand-only-for-last-commands
2184 (not (member last-command yas-expand-only-for-last-commands)))
2185 (setq templates-and-pos (if field
2187 (narrow-to-region (yas--field-start field)
2188 (yas--field-end field))
2190 (yas--current-key))))
2191 (if (and templates-and-pos
2192 (first templates-and-pos))
2193 (yas--expand-or-prompt-for-template (first templates-and-pos)
2194 (second templates-and-pos)
2195 (third templates-and-pos))
2198 (defun yas-expand-from-keymap ()
2199 "Directly expand some snippets, searching `yas--direct-keymaps'.
2201 If expansion fails, execute the previous binding for this key"
2203 (setq yas--condition-cache-timestamp (current-time))
2204 (let* ((vec (subseq (this-command-keys-vector) (if current-prefix-arg
2205 (length (this-command-keys))
2207 (templates (mapcan #'(lambda (table)
2208 (yas--fetch table vec))
2209 (yas--get-snippet-tables))))
2211 (yas--expand-or-prompt-for-template templates)
2212 (let ((yas-fallback-behavior 'call-other-command))
2215 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2216 "Expand one of TEMPLATES from START to END.
2218 Prompt the user if TEMPLATES has more than one element, else
2219 expand immediately. Common gateway for
2220 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2221 (let ((yas--current-template (or (and (rest templates) ;; more than one
2222 (yas--prompt-for-template (mapcar #'cdr templates)))
2224 (when yas--current-template
2225 (yas-expand-snippet (yas--template-content yas--current-template)
2228 (yas--template-expand-env yas--current-template)))))
2230 ;; Apropos the trigger key and the fallback binding:
2232 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2233 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2234 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2235 ;; improve this explanation.
2237 (defun yas--fallback ()
2238 "Fallback after expansion has failed.
2240 Common gateway for `yas-expand-from-trigger-key' and
2241 `yas-expand-from-keymap'."
2242 (cond ((eq yas-fallback-behavior 'return-nil)
2245 ((eq yas-fallback-behavior 'call-other-command)
2246 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2247 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2248 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2249 (setq this-original-command beyond-yasnippet)
2250 (call-interactively beyond-yasnippet)))
2251 ((and (listp yas-fallback-behavior)
2252 (cdr yas-fallback-behavior)
2253 (eq 'apply (car yas-fallback-behavior)))
2254 (if (cddr yas-fallback-behavior)
2255 (apply (cadr yas-fallback-behavior)
2256 (cddr yas-fallback-behavior))
2257 (when (commandp (cadr yas-fallback-behavior))
2258 (setq this-command (cadr yas-fallback-behavior))
2259 (call-interactively (cadr yas-fallback-behavior)))))
2261 ;; also return nil if all the other fallbacks have failed
2264 (defun yas--keybinding-beyond-yasnippet ()
2266 (let* ((yas-minor-mode nil)
2267 (yas--direct-keymaps nil)
2268 (keys (this-single-command-keys)))
2269 (or (key-binding keys t)
2270 (key-binding (yas--fallback-translate-input keys) t))))
2272 (defun yas--fallback-translate-input (keys)
2273 "Emulate `read-key-sequence', at least what I think it does.
2275 Keys should be an untranslated key vector. Returns a translated
2276 vector of keys. FIXME not thoroughly tested."
2279 (while (< i (length keys))
2281 (translated local-function-key-map))
2282 (while (and (< j (length keys))
2284 (keymapp translated))
2285 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2287 (setq retval (vconcat retval (cond ((symbolp translated)
2289 ((vectorp translated)
2292 (substring keys i j)))))
2297 ;;; Utils for snippet development:
2299 (defun yas--all-templates (tables)
2300 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2302 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2303 `yas-buffer-local-condition'"
2304 (when yas-choose-tables-first
2305 (setq tables (list (yas--prompt-for-table tables))))
2307 (if yas-choose-keys-first
2308 (let ((key (yas--prompt-for-keys
2309 (mapcan #'yas--table-all-keys tables))))
2311 (mapcan #'(lambda (table)
2312 (yas--fetch table key))
2314 (remove-duplicates (mapcan #'yas--table-templates tables)
2317 (defun yas-insert-snippet (&optional no-condition)
2318 "Choose a snippet to expand, pop-up a list of choices according
2319 to `yas--prompt-function'.
2321 With prefix argument NO-CONDITION, bypass filtering of snippets
2324 (setq yas--condition-cache-timestamp (current-time))
2325 (let* ((yas-buffer-local-condition (or (and no-condition
2327 yas-buffer-local-condition))
2328 (templates (yas--all-templates (yas--get-snippet-tables)))
2329 (yas--current-template (and templates
2330 (or (and (rest templates) ;; more than one template for same key
2331 (yas--prompt-for-template templates))
2333 (where (if (region-active-p)
2334 (cons (region-beginning) (region-end))
2335 (cons (point) (point)))))
2336 (if yas--current-template
2337 (yas-expand-snippet (yas--template-content yas--current-template)
2340 (yas--template-expand-env yas--current-template))
2341 (yas--message 3 "No snippets can be inserted here!"))))
2343 (defun yas-visit-snippet-file ()
2344 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2346 Only success if selected snippet was loaded from a file. Put the
2347 visited file in `snippet-mode'."
2349 (let* ((yas-buffer-local-condition 'always)
2350 (templates (yas--all-templates (yas--get-snippet-tables)))
2351 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2352 (template (and templates
2353 (or (yas--prompt-for-template templates
2354 "Choose a snippet template to edit: ")
2358 (yas--visit-snippet-file-1 template)
2359 (message "No snippets tables active!"))))
2361 (defun yas--visit-snippet-file-1 (template)
2362 "Helper for `yas-visit-snippet-file'."
2363 (let ((file (yas--template-file template)))
2364 (cond ((and file (file-readable-p file))
2365 (find-file-other-window file)
2367 (set (make-local-variable 'yas--editing-template) template))
2369 (message "Original file %s no longer exists!" file))
2371 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2372 (let ((type 'snippet))
2373 (when (listp (yas--template-content template))
2374 (insert (format "# type: command\n"))
2375 (setq type 'command))
2376 (insert (format "# key: %s\n" (yas--template-key template)))
2377 (insert (format "# name: %s\n" (yas--template-name template)))
2378 (when (yas--template-keybinding template)
2379 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2380 (when (yas--template-expand-env template)
2381 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2382 (when (yas--template-condition template)
2383 (insert (format "# condition: %s\n" (yas--template-condition template))))
2385 (insert (if (eq type 'command)
2386 (pp-to-string (yas--template-content template))
2387 (yas--template-content template))))
2389 (set (make-local-variable 'yas--editing-template) template)))))
2391 (defun yas--guess-snippet-directories-1 (table)
2392 "Guess possible snippet subdirectories for TABLE."
2393 (cons (yas--table-name table)
2394 (mapcan #'(lambda (parent)
2395 (yas--guess-snippet-directories-1
2397 (yas--table-parents table))))
2399 (defun yas--guess-snippet-directories (&optional table)
2400 "Try to guess suitable directories based on the current active
2401 tables (or optional TABLE).
2403 Returns a list of elements (TABLE . DIRS) where TABLE is a
2404 `yas--table' object and DIRS is a list of all possible directories
2405 where snippets of table might exist."
2406 (let ((main-dir (replace-regexp-in-string
2408 (or (first (or (yas-snippet-dirs)
2409 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2410 (tables (or (and table
2412 (yas--get-snippet-tables))))
2413 ;; HACK! the snippet table created here is actually registered!
2415 (unless (or table (gethash major-mode yas--tables))
2416 (push (yas--table-get-create major-mode)
2419 (mapcar #'(lambda (table)
2421 (mapcar #'(lambda (subdir)
2422 (concat main-dir "/" subdir))
2423 (yas--guess-snippet-directories-1 table))))
2426 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2427 "Return a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2428 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2429 (let ((candidate (first (cdr table-and-dirs))))
2430 (unless (file-writable-p (file-name-directory candidate))
2431 (error (yas--format "%s is not writable." candidate)))
2432 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2434 (if (gethash (yas--table-mode (car table-and-dirs))
2438 (or main-table-string
2440 (yas--table-name (car table-and-dirs))))
2442 (make-directory candidate 'also-make-parents)
2443 ;; create the .yas-parents file here...
2446 (defun yas-new-snippet (&optional no-template)
2447 "Pops a new buffer for writing a snippet.
2449 Expands a snippet-writing snippet, unless the optional prefix arg
2450 NO-TEMPLATE is non-nil."
2452 (let ((guessed-directories (yas--guess-snippet-directories)))
2454 (switch-to-buffer "*new snippet*")
2456 (kill-all-local-variables)
2459 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2460 (yas--table-mode (car d)))
2461 guessed-directories))
2462 (if (and (not no-template) yas-new-snippet-default)
2463 (yas-expand-snippet yas-new-snippet-default))))
2465 (defun yas--compute-major-mode-and-parents (file)
2466 "Given FILE, find the nearest snippet directory for a given mode.
2468 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2469 representing one or more of the mode's parents.
2471 Note that MODE-SYM need not be the symbol of a real major mode,
2472 neither do the elements of PARENTS."
2473 (let* ((file-dir (and file
2474 (directory-file-name (or (some #'(lambda (special)
2475 (locate-dominating-file file special))
2479 (directory-file-name (file-name-directory file))))))
2480 (parents-file-name (concat file-dir "/.yas-parents"))
2481 (major-mode-name (and file-dir
2482 (file-name-nondirectory file-dir)))
2483 (major-mode-sym (or (and major-mode-name
2484 (intern major-mode-name))))
2485 (parents (when (file-readable-p parents-file-name)
2489 (insert-file-contents parents-file-name)
2490 (buffer-substring-no-properties (point-min)
2492 (when major-mode-sym
2493 (cons major-mode-sym (remove major-mode-sym parents)))))
2495 (defvar yas--editing-template nil
2496 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2498 (defvar yas--current-template nil
2499 "Holds the current template being expanded into a snippet.")
2501 (defvar yas--guessed-modes nil
2502 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2504 (defun yas--read-table ()
2505 "Ask user for a snippet table, help with some guessing."
2506 (let ((prompt (if (and (featurep 'ido)
2508 'ido-completing-read 'completing-read)))
2509 (unless yas--guessed-modes
2510 (set (make-local-variable 'yas--guessed-modes)
2511 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2513 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2514 (if yas--guessed-modes
2515 (first yas--guessed-modes)
2517 (mapcar #'symbol-name yas--guessed-modes)
2522 (if (first yas--guessed-modes)
2523 (symbol-name (first yas--guessed-modes)))))))
2525 (defun yas-load-snippet-buffer (table &optional interactive)
2526 "Parse and load current buffer's snippet definition into TABLE.
2528 TABLE is a symbol naming a passed to `yas--table-get-create'.
2530 When called interactively, prompt for the table name."
2531 (interactive (list (yas--read-table) t))
2533 ;; We have `yas--editing-template', this buffer's content comes from a
2534 ;; template which is already loaded and neatly positioned,...
2536 (yas--editing-template
2537 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2538 (yas--template-table yas--editing-template)))
2539 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2540 ;; value from `yas--compute-major-mode-and-parents'
2543 (unless yas--guessed-modes
2544 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2545 (let* ((table (yas--table-get-create table)))
2546 (set (make-local-variable 'yas--editing-template)
2547 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2550 (yas--message 3 "Snippet \"%s\" loaded for %s."
2551 (yas--template-name yas--editing-template)
2552 (yas--table-name (yas--template-table yas--editing-template)))))
2554 (defun yas-load-snippet-buffer-and-close (table &optional kill)
2555 "Load the snippet with `yas-load-snippet-buffer', possibly
2556 save, then `quit-window' if saved.
2558 If the snippet is new, ask the user whether (and where) to save
2559 it. If the snippet already has a file, just save it.
2561 The prefix argument KILL is passed to `quit-window'.
2563 Don't use this from a Lisp program, call `yas-load-snippet-buffer'
2564 and `kill-buffer' instead."
2565 (interactive (list (yas--read-table) current-prefix-arg))
2566 (yas-load-snippet-buffer table t)
2568 ;; Only offer to save this if it looks like a library or new
2569 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2570 ;; which is not the first, or from an unwritable file)
2572 (not (yas--template-file yas--editing-template))
2573 (not (file-writable-p (yas--template-file yas--editing-template)))
2574 (and (listp yas-snippet-dirs)
2575 (second yas-snippet-dirs)
2576 (not (string-match (expand-file-name (first yas-snippet-dirs))
2577 (yas--template-file yas--editing-template)))))
2578 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2579 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2581 (yas--make-directory-maybe option))))
2583 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2584 (file-name-nondirectory (yas--template-file yas--editing-template)))
2585 (yas--template-name yas--editing-template))))
2586 (write-file (concat chosen "/"
2587 (read-from-minibuffer (format "File name to create in %s? " chosen)
2588 default-file-name)))
2589 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2590 (when buffer-file-name
2592 (quit-window kill)))
2594 (defun yas-tryout-snippet (&optional debug)
2595 "Test current buffer's snippet template in other buffer."
2597 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2598 (parsed (yas--parse-template))
2599 (test-mode (or (and (car major-mode-and-parent)
2600 (fboundp (car major-mode-and-parent))
2601 (car major-mode-and-parent))
2602 (first yas--guessed-modes)
2603 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2604 (yas--current-template
2607 (yas--populate-template (yas--make-blank-template)
2608 :table nil ;; no tables for ephemeral snippets
2610 :content (second parsed)
2611 :name (third parsed)
2612 :expand-env (sixth parsed)))))
2613 (cond (yas--current-template
2614 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2615 (kill-buffer (get-buffer-create buffer-name))
2616 (switch-to-buffer (get-buffer-create buffer-name))
2617 (setq buffer-undo-list nil)
2618 (condition-case nil (funcall test-mode) (error nil))
2620 (setq buffer-read-only nil)
2621 (yas-expand-snippet (yas--template-content yas--current-template)
2624 (yas--template-expand-env yas--current-template))
2626 (require 'yasnippet-debug nil t))
2627 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2629 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2631 (defun yas-active-keys ()
2632 "Return all active trigger keys for current buffer and point."
2634 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2637 (defun yas--template-fine-group (template)
2638 (car (last (or (yas--template-group template)
2639 (yas--template-perm-group template)))))
2641 (defun yas-describe-tables (&optional choose)
2642 "Display snippets for each table."
2644 (let* ((by-name-hash (and choose
2645 (y-or-n-p "Show by namehash? ")))
2646 (buffer (get-buffer-create "*YASnippet tables*"))
2647 (active-tables (yas--get-snippet-tables))
2648 (remain-tables (let ((all))
2649 (maphash #'(lambda (_k v)
2650 (unless (find v active-tables)
2654 (table-lists (list active-tables remain-tables))
2655 (original-buffer (current-buffer))
2657 (yas--condition-cache-timestamp (current-time)))
2658 (with-current-buffer buffer
2659 (setq buffer-read-only nil)
2661 (cond ((not by-name-hash)
2662 (insert "YASnippet tables: \n")
2663 (while (and table-lists
2665 (dolist (table (car table-lists))
2666 (yas--describe-pretty-table table original-buffer))
2667 (setq table-lists (cdr table-lists))
2669 (yas--create-snippet-xrefs)
2670 (display-buffer buffer)
2671 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2672 (yas--create-snippet-xrefs)
2676 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2677 (dolist (table (append active-tables remain-tables))
2678 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2680 (maphash #'(lambda (k _v)
2682 (yas--table-hash table))
2684 (insert (format " key %s maps snippets: %s\n" key
2686 (maphash #'(lambda (k _v)
2688 (gethash key (yas--table-hash table)))
2691 (setq buffer-read-only t))
2692 (display-buffer buffer)))
2694 (defun yas--describe-pretty-table (table &optional original-buffer)
2695 (insert (format "\nSnippet table `%s'"
2696 (yas--table-name table)))
2697 (if (yas--table-parents table)
2698 (insert (format " parents: %s\n"
2699 (mapcar #'yas--table-name
2700 (yas--table-parents table))))
2702 (insert (make-string 100 ?-) "\n")
2703 (insert "group state name key binding\n")
2704 (let ((groups-hash (make-hash-table :test #'equal)))
2705 (maphash #'(lambda (_k v)
2706 (let ((group (or (yas--template-fine-group v)
2708 (when (yas--template-name v)
2710 (cons v (gethash group groups-hash))
2712 (yas--table-uuidhash table))
2714 #'(lambda (group templates)
2715 (setq group (truncate-string-to-width group 25 0 ? "..."))
2716 (insert (make-string 100 ?-) "\n")
2717 (dolist (p templates)
2718 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2722 (setq group (make-string (length group) ? ))))
2723 (condition-string (let ((condition (yas--template-condition p)))
2726 (with-current-buffer original-buffer
2727 (if (yas--eval-condition condition)
2732 (insert condition-string " ")
2734 (if (string-match "\\.\\.\\.$" name)
2738 (insert (truncate-string-to-width (or (yas--template-key p) "")
2740 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2747 ;;; User convenience functions, for using in snippet definitions
2749 (defvar yas-modified-p nil
2750 "Non-nil if field has been modified by user or transformation.")
2752 (defvar yas-moving-away-p nil
2753 "Non-nil if user is about to exit field.")
2755 (defvar yas-text nil
2756 "Contains current field text.")
2758 (defun yas-substr (str pattern &optional subexp)
2759 "Search PATTERN in STR and return SUBEXPth match.
2761 If found, the content of subexp group SUBEXP (default 0) is
2762 returned, or else the original STR will be returned."
2763 (let ((grp (or subexp 0)))
2765 (if (string-match pattern str)
2766 (match-string-no-properties grp str)
2769 (defun yas-choose-value (&rest possibilities)
2770 "Prompt for a string in POSSIBILITIES and return it.
2772 The last element of POSSIBILITIES may be a list of strings."
2773 (unless (or yas-moving-away-p
2775 (setq possibilities (nreverse possibilities))
2776 (setq possibilities (if (listp (car possibilities))
2777 (append (reverse (car possibilities)) (rest possibilities))
2779 (some #'(lambda (fn)
2780 (funcall fn "Choose: " possibilities))
2781 yas-prompt-functions)))
2783 (defun yas-key-to-value (alist)
2784 (unless (or yas-moving-away-p
2786 (let ((key (read-key-sequence "")))
2788 (or (cdr (find key alist :key #'car :test #'string=))
2791 (defun yas-throw (text)
2792 "Throw a yas--exception with TEXT as the reason."
2793 (throw 'yas--exception (cons 'yas--exception text)))
2795 (defun yas-verify-value (possibilities)
2796 "Verify that the current field value is in POSSIBILITIES.
2798 Otherwise throw exception."
2799 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2800 (yas-throw (yas--format "Field only allows %s" possibilities))))
2802 (defun yas-field-value (number)
2803 "Get the string for field with NUMBER.
2805 Use this in primary and mirror transformations to tget."
2806 (let* ((snippet (car (yas--snippets-at-point)))
2808 (yas--snippet-find-field snippet number))))
2810 (yas--field-text-for-display field))))
2813 "Return `yas-text' if that exists and is non-empty, else nil."
2815 (not (string= "" yas-text)))
2818 (defun yas-selected-text ()
2819 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2820 (if (and yas-selected-text
2821 (not (string= "" yas-selected-text)))
2824 (defun yas--get-field-once (number &optional transform-fn)
2825 (unless yas-modified-p
2827 (funcall transform-fn (yas-field-value number))
2828 (yas-field-value number))))
2830 (defun yas-default-from-field (number)
2831 (unless yas-modified-p
2832 (yas-field-value number)))
2834 (defun yas-inside-string ()
2835 "Return non-nil if the point is inside a string according to font-lock."
2836 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2838 (defun yas-unimplemented (&optional missing-feature)
2839 (if yas--current-template
2840 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2843 (yas--visit-snippet-file-1 yas--current-template))
2844 (message "No implementation. Missing %s" (or missing-feature "something"))))
2847 ;;; Snippet expansion and field management
2849 (defvar yas--active-field-overlay nil
2850 "Overlays the currently active field.")
2852 (defvar yas--field-protection-overlays nil
2853 "Two overlays protect the current active field.")
2855 (defvar yas-selected-text nil
2856 "The selected region deleted on the last snippet expansion.")
2858 (defvar yas--start-column nil
2859 "The column where the snippet expansion started.")
2861 (make-variable-buffer-local 'yas--active-field-overlay)
2862 (make-variable-buffer-local 'yas--field-protection-overlays)
2863 (put 'yas--active-field-overlay 'permanent-local t)
2864 (put 'yas--field-protection-overlays 'permanent-local t)
2866 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2872 (id (yas--snippet-next-id) :read-only t)
2873 (control-overlay nil)
2875 ;; stacked expansion: the `previous-active-field' slot saves the
2876 ;; active field where the child expansion took place
2877 previous-active-field
2880 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2883 NUMBER is the field number.
2884 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2885 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2886 MIRRORS is a list of `yas--mirror's
2887 TRANSFORM is a lisp form.
2888 MODIFIED-P is a boolean set to true once user inputs text.
2889 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2900 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2903 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2904 TRANSFORM is a lisp form.
2905 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2906 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2907 DEPTH is a count of how many nested mirrors can affect this mirror"
2914 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2918 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2919 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2921 If there is no transform for ht field, return nil.
2923 If there is a transform but it returns nil, return the empty
2924 string iff EMPTY-ON-NIL-P is true."
2925 (let* ((yas-text (yas--field-text-for-display field))
2926 (yas-modified-p (yas--field-modified-p field))
2927 (yas-moving-away-p nil)
2928 (transform (if (yas--mirror-p field-or-mirror)
2929 (yas--mirror-transform field-or-mirror)
2930 (yas--field-transform field-or-mirror)))
2931 (start-point (if (yas--mirror-p field-or-mirror)
2932 (yas--mirror-start field-or-mirror)
2933 (yas--field-start field-or-mirror)))
2934 (transformed (and transform
2936 (goto-char start-point)
2937 (let ((ret (yas--eval-lisp transform)))
2938 (or ret (and empty-on-nil-p "")))))))
2941 (defsubst yas--replace-all (from to &optional text)
2942 "Replace all occurrences from FROM to TO.
2944 With optional string TEXT do it in that string."
2946 (replace-regexp-in-string (regexp-quote from) to text t t)
2947 (goto-char (point-min))
2948 (while (search-forward from nil t)
2949 (replace-match to t t text))))
2951 (defun yas--snippet-find-field (snippet number)
2952 (find-if #'(lambda (field)
2953 (eq number (yas--field-number field)))
2954 (yas--snippet-fields snippet)))
2956 (defun yas--snippet-sort-fields (snippet)
2957 "Sort the fields of SNIPPET in navigation order."
2958 (setf (yas--snippet-fields snippet)
2959 (sort (yas--snippet-fields snippet)
2960 #'yas--snippet-field-compare)))
2962 (defun yas--snippet-field-compare (field1 field2)
2963 "Compare FIELD1 and FIELD2.
2965 The field with a number is sorted first. If they both have a
2966 number, compare through the number. If neither have, compare
2967 through the field's start point"
2968 (let ((n1 (yas--field-number field1))
2969 (n2 (yas--field-number field2)))
2972 (or (zerop n2) (and (not (zerop n1))
2977 (< (yas--field-start field1)
2978 (yas--field-start field2))))))
2980 (defun yas--field-probably-deleted-p (snippet field)
2981 "Guess if SNIPPET's FIELD should be skipped."
2983 ;; field must be zero length
2985 (zerop (- (yas--field-start field) (yas--field-end field)))
2988 ;; 1) is a nested field and it's been modified
2990 (and (yas--field-parent-field field)
2991 (yas--field-modified-p field))
2992 ;; 2) ends just before the snippet end
2994 (and (eq field (car (last (yas--snippet-fields snippet))))
2995 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
2996 ;; the field numbered 0, just before the exit marker, should
2999 (not (zerop (yas--field-number field)))))
3001 (defun yas--snippets-at-point (&optional all-snippets)
3002 "Return a sorted list of snippets at point.
3004 The most recently-inserted snippets are returned first."
3006 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3007 (overlay-get ov 'yas--snippet))
3009 (overlays-in (point-min) (point-max))
3010 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3012 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3014 (defun yas-next-field-or-maybe-expand ()
3015 "Try to expand a snippet at a key before point.
3017 Otherwise delegate to `yas-next-field'."
3019 (if yas-triggers-in-field
3020 (let ((yas-fallback-behavior 'return-nil)
3021 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3023 (unless (yas-expand-from-trigger-key active-field)
3027 (defun yas-next-field (&optional arg)
3028 "Navigate to the ARGth next field.
3030 If there's none, exit the snippet."
3034 (snippet (first (yas--snippets-at-point)))
3035 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3036 (live-fields (remove-if #'(lambda (field)
3037 (and (not (eq field active-field))
3038 (yas--field-probably-deleted-p snippet field)))
3039 (yas--snippet-fields snippet)))
3040 (active-field-pos (position active-field live-fields))
3041 (target-pos (and active-field-pos (+ arg active-field-pos)))
3042 (target-field (and target-pos (nth target-pos live-fields))))
3043 ;; First check if we're moving out of a field with a transform
3045 (when (and active-field
3046 (yas--field-transform active-field))
3047 (let* ((yas-moving-away-p t)
3048 (yas-text (yas--field-text-for-display active-field))
3049 (yas-modified-p (yas--field-modified-p active-field)))
3050 ;; primary field transform: exit call to field-transform
3051 (yas--eval-lisp (yas--field-transform active-field))))
3052 ;; Now actually move...
3053 (cond ((and target-pos (>= target-pos (length live-fields)))
3054 (yas-exit-snippet snippet))
3056 (yas--move-to-field snippet target-field))
3060 (defun yas--place-overlays (snippet field)
3061 "Correctly place overlays for SNIPPET's FIELD."
3062 (yas--make-move-field-protection-overlays snippet field)
3063 (yas--make-move-active-field-overlay snippet field))
3065 (defun yas--move-to-field (snippet field)
3066 "Update SNIPPET to move to field FIELD.
3068 Also create some protection overlays"
3069 (goto-char (yas--field-start field))
3070 (yas--place-overlays snippet field)
3071 (overlay-put yas--active-field-overlay 'yas--field field)
3072 (let ((number (yas--field-number field)))
3073 ;; check for the special ${0: ...} field
3074 (if (and number (zerop number))
3076 (set-mark (yas--field-end field))
3077 (setf (yas--snippet-force-exit snippet)
3078 (or (yas--field-transform field)
3080 ;; make this field active
3081 (setf (yas--snippet-active-field snippet) field)
3082 ;; primary field transform: first call to snippet transform
3083 (unless (yas--field-modified-p field)
3084 (if (yas--field-update-display field)
3085 (yas--update-mirrors snippet)
3086 (setf (yas--field-modified-p field) nil))))))
3088 (defun yas-prev-field ()
3089 "Navigate to prev field. If there's none, exit the snippet."
3091 (yas-next-field -1))
3093 (defun yas-abort-snippet (&optional snippet)
3095 (let ((snippet (or snippet
3096 (car (yas--snippets-at-point)))))
3098 (setf (yas--snippet-force-exit snippet) t))))
3100 (defun yas-exit-snippet (snippet)
3101 "Goto exit-marker of SNIPPET."
3102 (interactive (list (first (yas--snippets-at-point))))
3104 (setf (yas--snippet-force-exit snippet) t)
3105 (goto-char (if (yas--snippet-exit snippet)
3106 (yas--exit-marker (yas--snippet-exit snippet))
3107 (overlay-end (yas--snippet-control-overlay snippet))))))
3109 (defun yas-exit-all-snippets ()
3110 "Exit all snippets."
3112 (mapc #'(lambda (snippet)
3113 (yas-exit-snippet snippet)
3114 (yas--check-commit-snippet))
3115 (yas--snippets-at-point 'all-snippets)))
3118 ;;; Some low level snippet-routines:
3120 (defvar yas--inhibit-overlay-hooks nil
3121 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3123 (defmacro yas--inhibit-overlay-hooks (&rest body)
3124 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3125 (declare (indent 0))
3126 `(let ((yas--inhibit-overlay-hooks t))
3129 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3130 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3132 (defun yas--commit-snippet (snippet)
3133 "Commit SNIPPET, but leave point as it is.
3135 This renders the snippet as ordinary text."
3137 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3139 ;; Save the end of the moribund snippet in case we need to revive it
3140 ;; its original expansion.
3142 (when (and control-overlay
3143 (overlay-buffer control-overlay))
3144 (setq yas-snippet-beg (overlay-start control-overlay))
3145 (setq yas-snippet-end (overlay-end control-overlay))
3146 (delete-overlay control-overlay))
3148 (yas--inhibit-overlay-hooks
3149 (when yas--active-field-overlay
3150 (delete-overlay yas--active-field-overlay))
3151 (when yas--field-protection-overlays
3152 (mapc #'delete-overlay yas--field-protection-overlays)))
3154 ;; stacked expansion: if the original expansion took place from a
3155 ;; field, make sure we advance it here at least to
3156 ;; `yas-snippet-end'...
3158 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3159 (when (and yas-snippet-end previous-field)
3160 (yas--advance-end-maybe previous-field yas-snippet-end)))
3162 ;; Convert all markers to points,
3164 (yas--markers-to-points snippet)
3166 ;; Take care of snippet revival
3168 (if yas-snippet-revival
3169 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3171 ;; Dismember the snippet... this is useful if we get called
3172 ;; again from `yas--take-care-of-redo'....
3173 (setf (yas--snippet-fields snippet) nil)))
3175 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3177 (defun yas--safely-run-hooks (hook-var)
3178 (condition-case error
3179 (run-hooks hook-var)
3181 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3184 (defun yas--check-commit-snippet ()
3185 "Check if point exited the currently active field of the snippet.
3187 If so cleans up the whole snippet up."
3188 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3189 (snippets-left snippets)
3190 (snippet-exit-transform))
3191 (dolist (snippet snippets)
3192 (let ((active-field (yas--snippet-active-field snippet)))
3193 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3194 (cond ((or snippet-exit-transform
3195 (not (and active-field (yas--field-contains-point-p active-field))))
3196 (setq snippets-left (delete snippet snippets-left))
3197 (setf (yas--snippet-force-exit snippet) nil)
3198 (yas--commit-snippet snippet))
3200 (or (not yas--active-field-overlay)
3201 (not (overlay-buffer yas--active-field-overlay))))
3203 ;; stacked expansion: this case is mainly for recent
3204 ;; snippet exits that place us back int the field of
3208 (yas--move-to-field snippet active-field)
3209 (yas--update-mirrors snippet)))
3212 (unless (or (null snippets) snippets-left)
3213 (if snippet-exit-transform
3214 (yas--eval-lisp-no-saves snippet-exit-transform))
3215 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3217 ;; Apropos markers-to-points:
3219 ;; This was found useful for performance reasons, so that an
3220 ;; excessive number of live markers aren't kept around in the
3221 ;; `buffer-undo-list'. However, in `markers-to-points', the
3222 ;; set-to-nil markers can't simply be discarded and replaced with
3223 ;; fresh ones in `points-to-markers'. The original marker that was
3224 ;; just set to nil has to be reused.
3226 ;; This shouldn't bring horrible problems with undo/redo, but it
3229 (defun yas--markers-to-points (snippet)
3230 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3231 where POINT is the original position of the marker and MARKER is
3232 the original marker object with the position set to nil."
3233 (dolist (field (yas--snippet-fields snippet))
3234 (let ((start (marker-position (yas--field-start field)))
3235 (end (marker-position (yas--field-end field))))
3236 (set-marker (yas--field-start field) nil)
3237 (set-marker (yas--field-end field) nil)
3238 (setf (yas--field-start field) (cons start (yas--field-start field)))
3239 (setf (yas--field-end field) (cons end (yas--field-end field))))
3240 (dolist (mirror (yas--field-mirrors field))
3241 (let ((start (marker-position (yas--mirror-start mirror)))
3242 (end (marker-position (yas--mirror-end mirror))))
3243 (set-marker (yas--mirror-start mirror) nil)
3244 (set-marker (yas--mirror-end mirror) nil)
3245 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3246 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3247 (let ((snippet-exit (yas--snippet-exit snippet)))
3249 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3250 (set-marker (yas--exit-marker snippet-exit) nil)
3251 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3253 (defun yas--points-to-markers (snippet)
3254 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3256 This is done by setting MARKER to POINT with `set-marker'."
3257 (dolist (field (yas--snippet-fields snippet))
3258 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3259 (car (yas--field-start field))))
3260 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3261 (car (yas--field-end field))))
3262 (dolist (mirror (yas--field-mirrors field))
3263 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3264 (car (yas--mirror-start mirror))))
3265 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3266 (car (yas--mirror-end mirror))))))
3267 (let ((snippet-exit (yas--snippet-exit snippet)))
3269 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3270 (car (yas--exit-marker snippet-exit)))))))
3272 (defun yas--field-contains-point-p (field &optional point)
3273 (let ((point (or point
3275 (and (>= point (yas--field-start field))
3276 (<= point (yas--field-end field)))))
3278 (defun yas--field-text-for-display (field)
3279 "Return the propertized display text for field FIELD."
3280 (buffer-substring (yas--field-start field) (yas--field-end field)))
3282 (defun yas--undo-in-progress ()
3283 "True if some kind of undo is in progress."
3284 (or undo-in-progress
3285 (eq this-command 'undo)
3286 (eq this-command 'redo)))
3288 (defun yas--make-control-overlay (snippet start end)
3289 "Create the control overlay that surrounds the snippet and
3291 (let ((overlay (make-overlay start
3296 (overlay-put overlay 'keymap yas-keymap)
3297 (overlay-put overlay 'priority 100)
3298 (overlay-put overlay 'yas--snippet snippet)
3301 (defun yas-skip-and-clear-or-delete-char (&optional field)
3302 "Clears unmodified field if at field start, skips to next tab.
3304 Otherwise deletes a character normally by calling `delete-char'."
3306 (let ((field (or field
3307 (and yas--active-field-overlay
3308 (overlay-buffer yas--active-field-overlay)
3309 (overlay-get yas--active-field-overlay 'yas--field)))))
3311 (not (yas--field-modified-p field))
3312 (eq (point) (marker-position (yas--field-start field))))
3313 (yas--skip-and-clear field)
3316 (call-interactively 'delete-char)))))
3318 (defun yas--skip-and-clear (field)
3319 "Deletes the region of FIELD and sets it's modified state to t."
3320 ;; Just before skipping-and-clearing the field, mark its children
3321 ;; fields as modified, too. If the children have mirrors-in-fields
3322 ;; this prevents them from updating erroneously (we're skipping and
3325 (yas--mark-this-and-children-modified field)
3326 (delete-region (yas--field-start field) (yas--field-end field)))
3328 (defun yas--mark-this-and-children-modified (field)
3329 (setf (yas--field-modified-p field) t)
3330 (let ((fom (yas--field-next field)))
3332 (yas--fom-parent-field fom))
3333 (when (and (eq (yas--fom-parent-field fom) field)
3335 (yas--mark-this-and-children-modified fom))
3336 (setq fom (yas--fom-next fom)))))
3338 (defun yas--make-move-active-field-overlay (snippet field)
3339 "Place the active field overlay in SNIPPET's FIELD.
3341 Move the overlay, or create it if it does not exit."
3342 (if (and yas--active-field-overlay
3343 (overlay-buffer yas--active-field-overlay))
3344 (move-overlay yas--active-field-overlay
3345 (yas--field-start field)
3346 (yas--field-end field))
3347 (setq yas--active-field-overlay
3348 (make-overlay (yas--field-start field)
3349 (yas--field-end field)
3351 (overlay-put yas--active-field-overlay 'priority 100)
3352 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3353 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3354 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3355 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3356 '(yas--on-field-overlay-modification))
3357 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3358 '(yas--on-field-overlay-modification))))
3360 (defun yas--on-field-overlay-modification (overlay after? _beg _end &optional _length)
3361 "Clears the field and updates mirrors, conditionally.
3363 Only clears the field if it hasn't been modified and it point it
3364 at field start. This hook doesn't do anything if an undo is in
3366 (unless (or yas--inhibit-overlay-hooks
3367 (yas--undo-in-progress))
3368 (let* ((field (overlay-get overlay 'yas--field))
3369 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3371 (yas--advance-end-maybe field (overlay-end overlay))
3373 (yas--field-update-display field))
3374 (yas--update-mirrors snippet))
3376 (when (and (not after?)
3377 (not (yas--field-modified-p field))
3378 (eq (point) (if (markerp (yas--field-start field))
3379 (marker-position (yas--field-start field))
3380 (yas--field-start field))))
3381 (yas--skip-and-clear field))
3382 (setf (yas--field-modified-p field) t))))))
3384 ;;; Apropos protection overlays:
3386 ;; These exist for nasty users who will try to delete parts of the
3387 ;; snippet outside the active field. Actual protection happens in
3388 ;; `yas--on-protection-overlay-modification'.
3390 ;; Currently this signals an error which inhibits the command. For
3391 ;; commands that move point (like `kill-line'), point is restored in
3392 ;; the `yas--post-command-handler' using a global
3393 ;; `yas--protection-violation' variable.
3395 ;; Alternatively, I've experimented with an implementation that
3396 ;; commits the snippet before actually calling `this-command'
3397 ;; interactively, and then signals an error, which is ignored. but
3398 ;; blocks all other million modification hooks. This presented some
3399 ;; problems with stacked expansion.
3401 (defun yas--make-move-field-protection-overlays (snippet field)
3402 "Place protection overlays surrounding SNIPPET's FIELD.
3404 Move the overlays, or create them if they do not exit."
3405 (let ((start (yas--field-start field))
3406 (end (yas--field-end field)))
3407 ;; First check if the (1+ end) is contained in the buffer,
3408 ;; otherwise we'll have to do a bit of cheating and silently
3409 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3410 ;; when using stacked expansion
3412 (when (< (buffer-size) end)
3414 (yas--inhibit-overlay-hooks
3415 (goto-char (point-max))
3417 ;; go on to normal overlay creation/moving
3419 (cond ((and yas--field-protection-overlays
3420 (every #'overlay-buffer yas--field-protection-overlays))
3421 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3422 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3424 (setq yas--field-protection-overlays
3425 (list (make-overlay (1- start) start nil t nil)
3426 (make-overlay end (1+ end) nil t nil)))
3427 (dolist (ov yas--field-protection-overlays)
3428 (overlay-put ov 'face 'yas--field-debug-face)
3429 (overlay-put ov 'yas--snippet snippet)
3430 ;; (overlay-put ov 'evaporate t)
3431 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3433 (defvar yas--protection-violation nil
3434 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3436 Functions in the `post-command-hook', for example
3437 `yas--post-command-handler' can check it and reset its value to
3438 nil. The variables value is the point where the violation
3441 (defun yas--on-protection-overlay-modification (_overlay after? _beg _end &optional _length)
3442 "Signals a snippet violation, then issues error.
3444 The error should be ignored in `debug-ignored-errors'"
3445 (unless yas--inhibit-overlay-hooks
3446 (cond ((not (or after?
3447 (yas--undo-in-progress)))
3448 (setq yas--protection-violation (point))
3449 (error "Exit the snippet first!")))))
3451 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3454 ;;; Snippet expansion and "stacked" expansion:
3456 ;; Stacked expansion is when you try to expand a snippet when already
3457 ;; inside a snippet expansion.
3459 ;; The parent snippet does not run its fields modification hooks
3460 ;; (`yas--on-field-overlay-modification' and
3461 ;; `yas--on-protection-overlay-modification') while the child snippet
3462 ;; is active. This means, among other things, that the mirrors of the
3463 ;; parent snippet are not updated, this only happening when one exits
3464 ;; the child snippet.
3466 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3467 ;; bits of code in `yas-expand-snippet' and
3468 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3471 ;; This was thought to be safer in an undo/redo perspective, but
3472 ;; maybe the correct implementation is to make the globals
3473 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3474 ;; snippet-local and be active even while the child snippet is
3475 ;; running. This would mean a lot of overlay modification hooks
3476 ;; running, but if managed correctly (including overlay priorities)
3477 ;; they should account for all situations...
3479 (defun yas-expand-snippet (content &optional start end expand-env)
3480 "Expand snippet CONTENT at current point.
3482 Text between START and END will be deleted before inserting
3483 template. EXPAND-ENV is are let-style variable to value bindings
3484 considered when expanding the snippet."
3485 (run-hooks 'yas-before-expand-snippet-hook)
3488 (let* ((yas-selected-text (or yas-selected-text
3489 (and (region-active-p)
3490 (buffer-substring-no-properties (region-beginning)
3493 (and (region-active-p)
3497 (and (region-active-p)
3500 (to-delete (and start
3502 (buffer-substring-no-properties start end)))
3505 (setq yas--indent-original-column (current-column))
3506 ;; Delete the region to delete, this *does* get undo-recorded.
3508 (when (and to-delete
3510 (delete-region start end))
3512 (cond ((listp content)
3513 ;; x) This is a snippet-command
3515 (yas--eval-lisp-no-saves content))
3517 ;; x) This is a snippet-snippet :-)
3519 ;; Narrow the region down to the content, shoosh the
3520 ;; `buffer-undo-list', and create the snippet, the new
3521 ;; snippet updates its mirrors once, so we are left with
3522 ;; some plain text. The undo action for deleting this
3523 ;; plain text will get recorded at the end.
3525 ;; stacked expansion: also shoosh the overlay modification hooks
3526 (let ((buffer-undo-list t))
3527 ;; snippet creation might evaluate users elisp, which
3528 ;; might generate errors, so we have to be ready to catch
3529 ;; them mostly to make the undo information
3531 (setq yas--start-column (current-column))
3532 (yas--inhibit-overlay-hooks
3535 (eval `(let* ,expand-env
3537 (yas--snippet-create start (point))))
3539 (yas--snippet-create start (point))))))
3541 ;; stacked-expansion: This checks for stacked expansion, save the
3542 ;; `yas--previous-active-field' and advance its boundary.
3544 (let ((existing-field (and yas--active-field-overlay
3545 (overlay-buffer yas--active-field-overlay)
3546 (overlay-get yas--active-field-overlay 'yas--field))))
3547 (when existing-field
3548 (setf (yas--snippet-previous-active-field snippet) existing-field)
3549 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3551 ;; Exit the snippet immediately if no fields
3553 (unless (yas--snippet-fields snippet)
3554 (yas-exit-snippet snippet))
3556 ;; Push two undo actions: the deletion of the inserted contents of
3557 ;; the new snippet (without the "key") followed by an apply of
3558 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3560 ;; A small exception, if `yas-also-auto-indent-first-line'
3561 ;; is t and `yas--indent' decides to indent the line to a
3562 ;; point before the actual expansion point, undo would be
3563 ;; messed up. We call the early point "newstart"". case,
3564 ;; and attempt to fix undo.
3566 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3567 (end (overlay-end (yas--snippet-control-overlay snippet))))
3568 (when (< newstart start)
3569 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3570 (push (cons newstart end) buffer-undo-list)
3571 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3573 ;; Now, schedule a move to the first field
3575 (let ((first-field (car (yas--snippet-fields snippet))))
3577 (sit-for 0) ;; fix issue 125
3578 (yas--move-to-field snippet first-field)))
3579 (yas--message 3 "snippet expanded.")
3582 (defun yas--take-care-of-redo (_beg _end snippet)
3583 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3585 Meant to exit in the `buffer-undo-list'."
3586 ;; slightly optimize: this action is only needed for snippets with
3587 ;; at least one field
3588 (when (yas--snippet-fields snippet)
3589 (yas--commit-snippet snippet)))
3591 (defun yas--snippet-revive (beg end snippet)
3592 "Revives SNIPPET and creates a control overlay from BEG to END.
3594 BEG and END are, we hope, the original snippets boundaries.
3595 All the markers/points exiting existing inside SNIPPET should point
3596 to their correct locations *at the time the snippet is revived*.
3598 After revival, push the `yas--take-care-of-redo' in the
3600 ;; Reconvert all the points to markers
3602 (yas--points-to-markers snippet)
3603 ;; When at least one editable field existed in the zombie snippet,
3604 ;; try to revive the whole thing...
3606 (let ((target-field (or (yas--snippet-active-field snippet)
3607 (car (yas--snippet-fields snippet)))))
3609 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3610 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3612 (yas--move-to-field snippet target-field)
3614 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3615 buffer-undo-list))))
3617 (defun yas--snippet-create (begin end)
3618 "Create a snippet from a template inserted at BEGIN to END.
3620 Returns the newly created snippet."
3622 (narrow-to-region begin end)
3623 (let ((snippet (yas--make-snippet)))
3625 (yas--snippet-parse-create snippet)
3627 ;; Sort and link each field
3628 (yas--snippet-sort-fields snippet)
3630 ;; Create keymap overlay for snippet
3631 (setf (yas--snippet-control-overlay snippet)
3632 (yas--make-control-overlay snippet (point-min) (point-max)))
3635 (goto-char (point-max))
3640 ;;; Apropos adjacencies and "fom's":
3642 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3643 ;; recently expanded snippet, we might actually have many fields,
3644 ;; mirrors (and the snippet exit) in the very same position in the
3645 ;; buffer. Therefore we need to single-link the
3646 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3647 ;; according to their original positions in the buffer.
3649 ;; Then we have operation `yas--advance-end-maybe' and
3650 ;; `yas--advance-start-maybe', which conditionally push the starts and
3651 ;; ends of these foms down the chain.
3653 ;; This allows for like the printf with the magic ",":
3655 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3656 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3658 (defun yas--fom-start (fom)
3659 (cond ((yas--field-p fom)
3660 (yas--field-start fom))
3661 ((yas--mirror-p fom)
3662 (yas--mirror-start fom))
3664 (yas--exit-marker fom))))
3666 (defun yas--fom-end (fom)
3667 (cond ((yas--field-p fom)
3668 (yas--field-end fom))
3669 ((yas--mirror-p fom)
3670 (yas--mirror-end fom))
3672 (yas--exit-marker fom))))
3674 (defun yas--fom-next (fom)
3675 (cond ((yas--field-p fom)
3676 (yas--field-next fom))
3677 ((yas--mirror-p fom)
3678 (yas--mirror-next fom))
3680 (yas--exit-next fom))))
3682 (defun yas--fom-parent-field (fom)
3683 (cond ((yas--field-p fom)
3684 (yas--field-parent-field fom))
3685 ((yas--mirror-p fom)
3686 (yas--mirror-parent-field fom))
3690 (defun yas--calculate-adjacencies (snippet)
3691 "Calculate adjacencies for fields or mirrors of SNIPPET.
3693 This is according to their relative positions in the buffer, and
3694 has to be called before the $-constructs are deleted."
3695 (let* ((fom-set-next-fom
3696 (lambda (fom nextfom)
3697 (cond ((yas--field-p fom)
3698 (setf (yas--field-next fom) nextfom))
3699 ((yas--mirror-p fom)
3700 (setf (yas--mirror-next fom) nextfom))
3702 (setf (yas--exit-next fom) nextfom)))))
3705 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3706 (yas--mirror-p fom2)
3707 (>= (yas--fom-start fom2) (yas--fom-start fom1)))))
3708 (link-foms fom-set-next-fom))
3709 ;; make some yas--field, yas--mirror and yas--exit soup
3711 (when (yas--snippet-exit snippet)
3712 (push (yas--snippet-exit snippet) soup))
3713 (dolist (field (yas--snippet-fields snippet))
3715 (dolist (mirror (yas--field-mirrors field))
3716 (push mirror soup)))
3718 (sort soup compare-fom-begs))
3720 (reduce link-foms soup)))))
3722 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3723 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3725 Use the tightest containing field if more than one field contains
3726 the mirror. Intended to be called *before* the dollar-regions are
3728 (let ((min (point-min))
3730 (dolist (field (yas--snippet-fields snippet))
3731 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3732 (<= (yas--mirror-end mirror) (yas--field-end field))
3733 (< min (yas--field-start field))
3734 (< (yas--field-end field) max))
3735 (setq min (yas--field-start field)
3736 max (yas--field-end field))
3737 (setf (yas--mirror-parent-field mirror) field)))))
3739 (defun yas--advance-end-maybe (fom newend)
3740 "Maybe advance FOM's end to NEWEND if it needs it.
3744 * call `yas--advance-start-maybe' on FOM's next fom.
3746 * in case FOM is field call `yas--advance-end-maybe' on its parent
3749 Also, if FOM is an exit-marker, always call
3750 `yas--advance-start-maybe' on its next fom. This is because
3751 exit-marker have identical start and end markers."
3752 (cond ((and fom (< (yas--fom-end fom) newend))
3753 (set-marker (yas--fom-end fom) newend)
3754 (yas--advance-start-maybe (yas--fom-next fom) newend)
3755 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3757 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3759 (defun yas--advance-start-maybe (fom newstart)
3760 "Maybe advance FOM's start to NEWSTART if it needs it.
3762 If it does, also call `yas--advance-end-maybe' on FOM."
3763 (when (and fom (< (yas--fom-start fom) newstart))
3764 (set-marker (yas--fom-start fom) newstart)
3765 (yas--advance-end-maybe fom newstart)))
3767 (defun yas--advance-end-of-parents-maybe (field newend)
3768 "Like `yas--advance-end-maybe' but for parent fields.
3770 Only works for fields and doesn't care about the start of the
3771 next FOM. Works its way up recursively for parents of parents."
3773 (< (yas--field-end field) newend))
3774 (set-marker (yas--field-end field) newend)
3775 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3777 (defvar yas--dollar-regions nil
3778 "When expanding the snippet the \"parse-create\" functions add
3779 cons cells to this var.")
3781 (defvar yas--backquote-markers-and-strings nil
3782 "List of (MARKER . STRING) marking where the values from
3783 backquoted Lisp expressions should be inserted at the end of
3786 (defun yas--snippet-parse-create (snippet)
3787 "Parse a recently inserted snippet template, creating all
3788 necessary fields, mirrors and exit points.
3790 Meant to be called in a narrowed buffer, does various passes"
3791 (let ((parse-start (point)))
3792 ;; Reset the yas--dollar-regions
3794 (setq yas--dollar-regions nil)
3795 ;; protect just the backquotes
3797 (yas--protect-escapes nil '(?`))
3798 ;; replace all backquoted expressions
3800 (goto-char parse-start)
3801 (yas--save-backquotes)
3802 ;; protect escaped characters
3804 (yas--protect-escapes)
3805 ;; parse fields with {}
3807 (goto-char parse-start)
3808 (yas--field-parse-create snippet)
3809 ;; parse simple mirrors and fields
3811 (goto-char parse-start)
3812 (yas--simple-mirror-parse-create snippet)
3813 ;; parse mirror transforms
3815 (goto-char parse-start)
3816 (yas--transform-mirror-parse-create snippet)
3817 ;; calculate adjacencies of fields and mirrors
3819 (yas--calculate-adjacencies snippet)
3820 ;; Delete $-constructs
3822 (yas--delete-regions yas--dollar-regions)
3823 ;; restore backquoted expression values
3825 (yas--restore-backquotes)
3828 (goto-char parse-start)
3829 (yas--restore-escapes)
3830 ;; update mirrors for the first time
3832 (yas--update-mirrors snippet)
3833 ;; indent the best we can
3835 (goto-char parse-start)
3836 (yas--indent snippet)))
3838 (defun yas--indent-according-to-mode (snippet-markers)
3839 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3840 ;;; Apropos indenting problems....
3842 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3843 ;; is available. Some implementations of these functions delete text
3844 ;; before they insert. If there happens to be a marker just after
3845 ;; the text being deleted, the insertion actually happens after the
3846 ;; marker, which misplaces it.
3848 ;; This would also happen if we had used overlays with the
3849 ;; `front-advance' property set to nil.
3851 ;; This is why I have these `trouble-markers', they are the ones at
3852 ;; they are the ones at the first non-whitespace char at the line
3853 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3854 ;; we should be at the correct to restore them to. All other
3855 ;; non-trouble-markers have been *pushed* and don't need special
3858 (goto-char (yas--real-line-beginning))
3859 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3865 (indent-according-to-mode)
3866 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3868 (mapc #'(lambda (marker)
3869 (set-marker marker (point)))
3872 (defvar yas--indent-original-column nil)
3873 (defun yas--indent (snippet)
3874 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3875 ;; Look for those $>
3877 (while (re-search-forward "$>" nil t)
3878 (delete-region (match-beginning 0) (match-end 0))
3879 (when (not (eq yas-indent-line 'auto))
3880 (yas--indent-according-to-mode snippet-markers))))
3881 ;; Now do stuff for 'fixed and 'auto
3883 (cond ((eq yas-indent-line 'fixed)
3884 (while (and (zerop (forward-line))
3885 (zerop (current-column)))
3886 (indent-to-column yas--indent-original-column)))
3887 ((eq yas-indent-line 'auto)
3888 (let ((end (set-marker (make-marker) (point-max)))
3889 (indent-first-line-p yas-also-auto-indent-first-line))
3890 (while (and (zerop (if indent-first-line-p
3893 (setq indent-first-line-p nil))
3897 (yas--indent-according-to-mode snippet-markers))))
3901 (defun yas--collect-snippet-markers (snippet)
3902 "Make a list of all the markers used by SNIPPET."
3904 (dolist (field (yas--snippet-fields snippet))
3905 (push (yas--field-start field) markers)
3906 (push (yas--field-end field) markers)
3907 (dolist (mirror (yas--field-mirrors field))
3908 (push (yas--mirror-start mirror) markers)
3909 (push (yas--mirror-end mirror) markers)))
3910 (let ((snippet-exit (yas--snippet-exit snippet)))
3911 (when (and snippet-exit
3912 (marker-buffer (yas--exit-marker snippet-exit)))
3913 (push (yas--exit-marker snippet-exit) markers)))
3916 (defun yas--real-line-beginning ()
3917 (let ((c (char-after (line-beginning-position)))
3918 (n (line-beginning-position)))
3919 (while (or (eql c ?\ )
3922 (setq c (char-after n)))
3925 (defun yas--escape-string (escaped)
3926 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3928 (defun yas--protect-escapes (&optional text escaped)
3929 "Protect all escaped characters with their numeric ASCII value.
3931 With optional string TEXT do it in string instead of buffer."
3932 (let ((changed-text text)
3933 (text-provided-p text))
3934 (mapc #'(lambda (escaped)
3936 (yas--replace-all (concat "\\" (char-to-string escaped))
3937 (yas--escape-string escaped)
3938 (when text-provided-p changed-text))))
3939 (or escaped yas--escaped-characters))
3942 (defun yas--restore-escapes (&optional text escaped)
3943 "Restore all escaped characters from their numeric ASCII value.
3945 With optional string TEXT do it in string instead of the buffer."
3946 (let ((changed-text text)
3947 (text-provided-p text))
3948 (mapc #'(lambda (escaped)
3950 (yas--replace-all (yas--escape-string escaped)
3951 (char-to-string escaped)
3952 (when text-provided-p changed-text))))
3953 (or escaped yas--escaped-characters))
3956 (defun yas--save-backquotes ()
3957 "Save all the \"`(lisp-expression)`\"-style expressions
3958 with their evaluated value into `yas--backquote-markers-and-strings'."
3959 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
3960 (let ((current-string (match-string-no-properties 1)) transformed)
3961 (delete-region (match-beginning 0) (match-end 0))
3962 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
3963 (goto-char (match-beginning 0))
3965 (let ((marker (make-marker)))
3966 (insert "Y") ;; quite horrendous, I love it :)
3967 (set-marker marker (point))
3969 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
3971 (defun yas--restore-backquotes ()
3972 "Replace markers in `yas--backquote-markers-and-strings' with their values."
3973 (while yas--backquote-markers-and-strings
3974 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
3975 (marker (car marker-and-string))
3976 (string (cdr marker-and-string)))
3982 (set-marker marker nil)))))
3984 (defun yas--scan-sexps (from count)
3986 (with-syntax-table (standard-syntax-table)
3987 (scan-sexps from count))
3991 (defun yas--make-marker (pos)
3992 "Create a marker at POS with nil `marker-insertion-type'."
3993 (let ((marker (set-marker (make-marker) pos)))
3994 (set-marker-insertion-type marker nil)
3997 (defun yas--field-parse-create (snippet &optional parent-field)
3998 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4000 The following count as a field:
4002 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4004 * \"${n: text$(expression)}, the same with a Lisp expression;
4005 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4007 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4009 When multiple expressions are found, only the last one counts."
4012 (while (re-search-forward yas--field-regexp nil t)
4013 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4014 (number (and (match-string-no-properties 1)
4015 (string-to-number (match-string-no-properties 1))))
4016 (brand-new-field (and real-match-end-0
4017 ;; break if on "$(" immediately
4018 ;; after the ":", this will be
4019 ;; caught as a mirror with
4021 (not (save-match-data
4022 (eq (string-match "$[ \t\n]*("
4023 (match-string-no-properties 2)) 0)))
4024 ;; allow ${0: some exit text}
4025 ;; (not (and number (zerop number)))
4026 (yas--make-field number
4027 (yas--make-marker (match-beginning 2))
4028 (yas--make-marker (1- real-match-end-0))
4030 (when brand-new-field
4031 (goto-char real-match-end-0)
4032 (push (cons (1- real-match-end-0) real-match-end-0)
4033 yas--dollar-regions)
4034 (push (cons (match-beginning 0) (match-beginning 2))
4035 yas--dollar-regions)
4036 (push brand-new-field (yas--snippet-fields snippet))
4039 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4040 (goto-char (point-min))
4041 (yas--field-parse-create snippet brand-new-field)))))))
4042 ;; if we entered from a parent field, now search for the
4043 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4044 ;; primary field transformations
4048 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4049 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4050 ;; commit the primary field transformation if:
4052 ;; 1. we don't find it in yas--dollar-regions (a subnested
4053 ;; field) might have already caught it.
4055 ;; 2. we really make sure we have either two '$' or some
4056 ;; text and a '$' after the colon ':'. This is a FIXME: work
4057 ;; my regular expressions and end these ugly hacks.
4059 (when (and real-match-end-1
4060 (not (member (cons (match-beginning 0)
4062 yas--dollar-regions))
4064 (char-before (1- (match-beginning 1))))))
4065 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4067 (setf (yas--field-transform parent-field)
4068 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4069 (push (cons (match-beginning 0) real-match-end-1)
4070 yas--dollar-regions)))))))
4072 (defun yas--transform-mirror-parse-create (snippet)
4073 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4074 (while (re-search-forward yas--transform-mirror-regexp nil t)
4075 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4076 (number (string-to-number (match-string-no-properties 1)))
4078 (not (zerop number))
4079 (yas--snippet-find-field snippet number)))
4081 (and real-match-end-0
4083 (yas--make-mirror (yas--make-marker (match-beginning 0))
4084 (yas--make-marker (match-beginning 0))
4086 (yas--restore-escapes
4087 (buffer-substring-no-properties (match-beginning 2)
4088 (1- real-match-end-0))))))))
4089 (when brand-new-mirror
4090 (push brand-new-mirror
4091 (yas--field-mirrors field))
4092 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4093 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4095 (defun yas--simple-mirror-parse-create (snippet)
4096 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4097 (while (re-search-forward yas--simple-mirror-regexp nil t)
4098 (let ((number (string-to-number (match-string-no-properties 1))))
4099 (cond ((zerop number)
4101 (setf (yas--snippet-exit snippet)
4102 (yas--make-exit (yas--make-marker (match-end 0))))
4104 (goto-char (match-beginning 0))
4105 (when yas-wrap-around-region
4106 (cond (yas-selected-text
4107 (insert yas-selected-text))
4108 ((and (eq yas-wrap-around-region 'cua)
4111 (insert (prog1 (get-register ?0)
4112 (set-register ?0 nil))))))
4113 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4114 yas--dollar-regions)))
4116 (let ((field (yas--snippet-find-field snippet number)))
4118 (let ((brand-new-mirror (yas--make-mirror
4119 (yas--make-marker (match-beginning 0))
4120 (yas--make-marker (match-beginning 0))
4122 (push brand-new-mirror
4123 (yas--field-mirrors field))
4124 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4125 (push (yas--make-field number
4126 (yas--make-marker (match-beginning 0))
4127 (yas--make-marker (match-beginning 0))
4129 (yas--snippet-fields snippet))))
4130 (push (cons (match-beginning 0) (match-end 0))
4131 yas--dollar-regions))))))
4133 (defun yas--delete-regions (regions)
4134 "Sort disjuct REGIONS by start point, then delete from the back."
4135 (mapc #'(lambda (reg)
4136 (delete-region (car reg) (cdr reg)))
4139 (>= (car r1) (car r2))))))
4141 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4142 (let* ((parent (yas--mirror-parent-field mirror))
4143 (parents-mirrors (and parent
4144 (yas--field-mirrors parent))))
4145 (or (yas--mirror-depth mirror)
4146 (setf (yas--mirror-depth mirror)
4147 (cond ((memq mirror traversed)
4149 ((and parent parents-mirrors)
4151 (mapcar #'(lambda (m)
4152 (yas--calculate-mirror-depth m
4161 (defun yas--update-mirrors (snippet)
4162 "Update all the mirrors of SNIPPET."
4164 (dolist (field-and-mirror (sort
4165 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4166 ;; where F is the field that M is mirroring
4168 (mapcan #'(lambda (field)
4169 (mapcar #'(lambda (mirror)
4170 (cons field mirror))
4171 (yas--field-mirrors field)))
4172 (yas--snippet-fields snippet))
4173 ;; then sort this list so that entries with mirrors with parent
4174 ;; fields appear before. This was important for fixing #290, and
4175 ;; luckily also handles the case where a mirror in a field causes
4176 ;; another mirror to need reupdating
4178 #'(lambda (field-and-mirror1 field-and-mirror2)
4179 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4180 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4181 (let* ((field (car field-and-mirror))
4182 (mirror (cdr field-and-mirror))
4183 (parent-field (yas--mirror-parent-field mirror)))
4184 ;; before updating a mirror with a parent-field, maybe advance
4188 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4189 ;; update this mirror
4191 (yas--mirror-update-display mirror field)
4192 ;; `yas--place-overlays' is needed if the active field and
4193 ;; protected overlays have been changed because of insertions
4194 ;; in `yas--mirror-update-display'
4196 (when (eq field (yas--snippet-active-field snippet))
4197 (yas--place-overlays snippet field))))))
4199 (defun yas--mirror-update-display (mirror field)
4200 "Update MIRROR according to FIELD (and mirror transform)."
4202 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4203 (reflection (and (not (and mirror-parent-field
4204 (yas--field-modified-p mirror-parent-field)))
4205 (or (yas--apply-transform mirror field 'empty-on-nil)
4206 (yas--field-text-for-display field)))))
4207 (when (and reflection
4208 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4209 (yas--mirror-end mirror)))))
4210 (goto-char (yas--mirror-start mirror))
4211 (yas--inhibit-overlay-hooks
4212 (insert reflection))
4213 (if (> (yas--mirror-end mirror) (point))
4214 (delete-region (point) (yas--mirror-end mirror))
4215 (set-marker (yas--mirror-end mirror) (point))
4216 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4217 ;; super-special advance
4218 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4220 (defun yas--field-update-display (field)
4221 "Much like `yas--mirror-update-display', but for fields."
4222 (when (yas--field-transform field)
4223 (let ((transformed (and (not (eq (yas--field-number field) 0))
4224 (yas--apply-transform field field))))
4225 (when (and transformed
4226 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4227 (yas--field-end field)))))
4228 (setf (yas--field-modified-p field) t)
4229 (goto-char (yas--field-start field))
4230 (yas--inhibit-overlay-hooks
4231 (insert transformed)
4232 (if (> (yas--field-end field) (point))
4233 (delete-region (point) (yas--field-end field))
4234 (set-marker (yas--field-end field) (point))
4235 (yas--advance-start-maybe (yas--field-next field) (point)))
4239 ;;; Post-command hook:
4241 (defun yas--post-command-handler ()
4242 "Handles various yasnippet conditions after each command."
4243 (cond (yas--protection-violation
4244 (goto-char yas--protection-violation)
4245 (setq yas--protection-violation nil))
4246 ((eq 'undo this-command)
4248 ;; After undo revival the correct field is sometimes not
4249 ;; restored correctly, this condition handles that
4251 (let* ((snippet (car (yas--snippets-at-point)))
4252 (target-field (and snippet
4253 (find-if-not #'(lambda (field)
4254 (yas--field-probably-deleted-p snippet field))
4256 (cons (yas--snippet-active-field snippet)
4257 (yas--snippet-fields snippet)))))))
4259 (yas--move-to-field snippet target-field))))
4260 ((not (yas--undo-in-progress))
4261 ;; When not in an undo, check if we must commit the snippet
4262 ;; (user exited it).
4263 (yas--check-commit-snippet))))
4267 ;; The docstrings for some functions are generated dynamically
4268 ;; depending on the context.
4270 (put 'yas-expand 'function-documentation
4271 '(yas--expand-from-trigger-key-doc))
4272 (defun yas--expand-from-trigger-key-doc ()
4273 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4274 (let ((fallback-description
4275 (cond ((eq yas-fallback-behavior 'call-other-command)
4276 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4278 (format " call command `%s'." (pp-to-string fallback)))
4279 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4280 ((eq yas-fallback-behavior 'return-nil)
4283 ", defer to `yas-fallback-behaviour' (which see)"))))
4284 (concat "Expand a snippet before point. If no snippet
4285 expansion is possible,"
4286 fallback-description
4287 "\n\nOptional argument FIELD is for non-interactive use and is an
4288 object satisfying `yas--field-p' to restrict the expansion to.")))
4290 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4291 (defun yas--expand-from-keymap-doc ()
4292 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4293 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4294 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4295 (when (eq this-command 'describe-key)
4296 (let* ((vec (this-single-command-keys))
4297 (templates (mapcan #'(lambda (table)
4298 (yas--fetch table vec))
4299 (yas--get-snippet-tables)))
4300 (yas--direct-keymaps nil)
4301 (fallback (key-binding vec)))
4302 (concat "In this case, "
4304 (concat "these snippets are bound to this key:\n"
4305 (yas--template-pretty-list templates)
4306 "\n\nIf none of these expands, "))
4308 (format "fallback `%s' will be called." (pp-to-string fallback)))
4309 "no fallback keybinding is called."))))))
4311 (defun yas--template-pretty-list (templates)
4313 (yas-buffer-local-condition 'always))
4314 (dolist (plate templates)
4315 (setq acc (concat acc "\n*) "
4316 (propertize (concat "\\\\snippet `" (car plate) "'")
4317 'yasnippet (cdr plate)))))
4320 (define-button-type 'help-snippet-def
4321 :supertype 'help-xref
4322 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4323 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4325 (defun yas--snippet-description-finish-runonce ()
4326 "Final adjustments for the help buffer when snippets are concerned."
4327 (yas--create-snippet-xrefs)
4328 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4330 (defun yas--create-snippet-xrefs ()
4332 (goto-char (point-min))
4333 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4334 (let ((template (get-text-property (match-beginning 1)
4337 (help-xref-button 1 'help-snippet-def template)
4338 (kill-region (match-end 1) (match-end 0))
4339 (kill-region (match-beginning 0) (match-beginning 1)))))))
4343 (defvar yas-verbosity 4
4344 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4346 (defun yas--message (level message &rest args)
4347 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4348 (when (> yas-verbosity level)
4349 (message "%s" (apply #'yas--format message args))))
4351 (defun yas--format (format-control &rest format-args)
4352 (apply #'format (concat "[yas] " format-control) format-args))
4359 ;; `locate-dominating-file'
4360 ;; `region-active-p'
4362 ;; added for compatibility in emacsen < 23
4363 (unless (>= emacs-major-version 23)
4364 (unless (fboundp 'region-active-p)
4365 (defun region-active-p () (and transient-mark-mode mark-active)))
4367 (unless (fboundp 'locate-dominating-file)
4368 (defvar locate-dominating-stop-dir-regexp
4369 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4370 "Regexp of directory names which stop the search in `locate-dominating-file'.
4371 Any directory whose name matches this regexp will be treated like
4372 a kind of root directory by `locate-dominating-file' which will stop its search
4373 when it bumps into it.
4374 The default regexp prevents fruitless and time-consuming attempts to find
4375 special files in directories in which filenames are interpreted as hostnames,
4376 or mount points potentially requiring authentication as a different user.")
4378 (defun locate-dominating-file (file name)
4379 "Look up the directory hierarchy from FILE for a file named NAME.
4380 Stop at the first parent directory containing a file NAME,
4381 and return the directory. Return nil if not found."
4382 ;; We used to use the above locate-dominating-files code, but the
4383 ;; directory-files call is very costly, so we're much better off doing
4384 ;; multiple calls using the code in here.
4386 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4387 ;; `name' in /home or in /.
4388 (setq file (abbreviate-file-name file))
4391 (while (not (or root
4393 ;; FIXME: Disabled this heuristic because it is sometimes
4395 ;; As a heuristic, we stop looking up the hierarchy of
4396 ;; directories as soon as we find a directory belonging
4397 ;; to another user. This should save us from looking in
4398 ;; things like /net and /afs. This assumes that all the
4399 ;; files inside a project belong to the same user.
4400 ;; (let ((prev-user user))
4401 ;; (setq user (nth 2 (file-attributes file)))
4402 ;; (and prev-user (not (equal user prev-user))))
4403 (string-match locate-dominating-stop-dir-regexp file)))
4404 (setq try (file-exists-p (expand-file-name name file)))
4405 (cond (try (setq root file))
4406 ((equal file (setq file (file-name-directory
4407 (directory-file-name file))))
4412 ;;; Backward compatibility to yasnippet <= 0.7
4414 (defvar yas--exported-syms '(;; `defcustom's
4417 yas-prompt-functions
4419 yas-also-auto-indent-first-line
4421 yas-triggers-in-field
4422 yas-fallback-behavior
4423 yas-choose-keys-first
4424 yas-choose-tables-first
4427 yas-wrap-around-region
4430 yas-expand-only-for-last-commands
4431 yas-field-highlight-face
4433 ;; these vars can be customized as well
4439 yas-after-exit-snippet-hook
4440 yas-before-expand-snippet-hook
4441 yas-buffer-local-condition
4444 ;; prompting functions
4449 yas-completing-prompt
4452 ;; interactive functions
4457 yas-direct-keymaps-reload
4461 yas-compile-directory
4464 yas-expand-from-trigger-key
4465 yas-expand-from-keymap
4467 yas-visit-snippet-file
4469 yas-load-snippet-buffer
4472 yas-next-field-or-maybe-expand
4477 yas-exit-all-snippets
4478 yas-skip-and-clear-or-delete-char
4480 ;; symbols that I "exported" for use
4481 ;; in snippets and hookage
4499 yas-default-from-field
4502 yas-define-condition-cache
4503 yas-hippie-try-expand
4506 ;; debug definitions
4507 ;; yas-debug-snippet-vars
4508 ;; yas-exterminate-package
4511 ;; testing definitions
4512 ;; yas-should-expand
4513 ;; yas-should-not-expand
4515 ;; yas-make-file-or-dirs
4517 ;; yas-saving-variables
4518 ;; yas-call-with-snippet-dirs
4519 ;; yas-with-snippet-dirs
4521 "Exported yasnippet symbols.
4523 i.e. ones that I will try to keep in future yasnippet versions
4524 and ones that other elisp libraries can more or less safely rely
4527 (defvar yas--dont-backport '(yas-active-keys)
4528 "Exported symbols that don't map back to \"yas/*\" variants.")
4530 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4531 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4533 (make-obsolete-variable backported sym "yasnippet 0.8")
4534 (defvaralias backported sym))
4536 (make-obsolete backported sym "yasnippet 0.8")
4537 (defalias backported sym))))
4540 (provide 'yasnippet)
4542 ;;; yasnippet.el ends here
4545 ;; byte-compile-warnings: (not cl-functions)