1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://code.google.com/p/yasnippet/
10 ;; Keywords: convenience, emulation
11 ;; URL: http://code.google.com/p/yasnippet/
12 ;; EmacsWiki: YaSnippetMode
14 ;; This file is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; This file is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
31 ;; Basic steps to setup:
33 ;; 1. In your .emacs file:
34 ;; (add-to-list 'load-path "/dir/to/yasnippet.el")
35 ;; (require 'yasnippet)
36 ;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets
37 ;; 3. In your .emacs file
38 ;; (setq yas/snippet-dirs "~/.emacs/snippets")
39 ;; (yas/load-directory yas/snippet-dirs)
40 ;; 4. To enable the YASnippet menu and tab-trigger expansion
42 ;; 5. To globally enable the minor mode in *all* buffers
43 ;; M-x yas/global-mode
45 ;; Steps 4. and 5. are optional, you don't have to use the minor
46 ;; mode to use YASnippet.
48 ;; Interesting variables are:
52 ;; The directory where user-created snippets are to be
53 ;; stored. Can also be a list of directories. In that case,
54 ;; when used for bulk (re)loading of snippets (at startup or
55 ;; via `yas/reload-all'), directories appearing earlier in
56 ;; the list shadow other dir's snippets. Also, the first
57 ;; directory is taken as the default for storing the user's new snippets.
61 ;; A local variable that you can set in a hook to override
62 ;; snippet-lookup based on major mode. It is a a symbol (or
63 ;; list of symbols) that correspond to subdirectories of
64 ;; `yas/snippet-dirs' and is used for deciding which
65 ;; snippets to consider for the active buffer.
67 ;; Major commands are:
71 ;; Try to expand snippets before point. In `yas/minor-mode',
72 ;; this is bound to `yas/trigger-key' which you can customize.
74 ;; M-x yas/load-directory
76 ;; Prompts you for a directory hierarchy of snippets to load.
78 ;; M-x yas/insert-snippet
80 ;; Prompts you for possible snippet expansion if that is
81 ;; possible according to buffer-local and snippet-local
82 ;; expansion conditions. With prefix argument, ignore these
85 ;; M-x yas/find-snippets
87 ;; Lets you find the snippet files in the correct
88 ;; subdirectory of `yas/snippet-dirs', according to the
89 ;; active major mode (if it exists) like
90 ;; `find-file-other-window'.
92 ;; M-x yas/visit-snippet-file
94 ;; Prompts you for possible snippet expansions like
95 ;; `yas/insert-snippet', but instead of expanding it, takes
96 ;; you directly to the snippet definition's file, if it
99 ;; M-x yas/new-snippet
101 ;; Lets you create a new snippet file in the correct
102 ;; subdirectory of `yas/snippet-dirs', according to the
103 ;; active major mode.
105 ;; M-x yas/load-snippet-buffer
107 ;; When editing a snippet, this loads the snippet. This is
108 ;; bound to "C-c C-c" while in the `snippet-mode' editing
111 ;; M-x yas/tryout-snippet
113 ;; When editing a snippet, this opens a new empty buffer,
114 ;; sets it to the appropriate major mode and inserts the
115 ;; snippet there, so you can see what it looks like. This is
116 ;; bound to "C-c C-t" while in `snippet-mode'.
118 ;; M-x yas/describe-tables
120 ;; Lists known snippets in a separate buffer. User is
121 ;; prompted as to whether only the currently active tables
122 ;; are to be displayed, or all the tables for all major
125 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
126 ;; can optionally use it the preferred "prompting method", puting in
127 ;; your .emacs file, for example:
129 ;; (require 'dropdown-list)
130 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
132 ;; yas/completing-prompt))
134 ;; Also check out the customization group
136 ;; M-x customize-group RET yasnippet RET
138 ;; If you use the customization group to set variables
139 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
140 ;; "yasnippet.el" is present in the `load-path' *before* the
141 ;; `custom-set-variables' is executed in your .emacs file.
143 ;; For more information and detailed usage, refer to the project page:
144 ;; http://code.google.com/p/yasnippet/
154 ;;; User customizable variables
156 (defgroup yasnippet nil
157 "Yet Another Snippet extension"
161 (defcustom yas/snippet-dirs nil
162 "Directory or list of snippet dirs for each major mode.
164 The directory where user-created snippets are to be stored. Can
165 also be a list of directories. In that case, when used for
166 bulk (re)loading of snippets (at startup or via
167 `yas/reload-all'), directories appearing earlier in the list
168 shadow other dir's snippets. Also, the first directory is taken
169 as the default for storing the user's new snippets."
170 :type '(choice (string :tag "Single directory (string)")
171 (repeat :args (string) :tag "List of directories (strings)"))
174 :set #'(lambda (symbol new)
175 (let ((old (and (boundp symbol)
176 (symbol-value symbol))))
177 (set-default symbol new)
178 (unless (or (not (fboundp 'yas/reload-all))
181 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
183 (defcustom yas/prompt-functions '(yas/x-prompt
185 yas/completing-prompt
188 "Functions to prompt for keys, templates, etc interactively.
190 These functions are called with the following arguments:
192 - PROMPT: A string to prompt the user
194 - CHOICES: a list of strings or objects.
196 - optional DISPLAY-FN : A function that, when applied to each of
197 the objects in CHOICES will return a string.
199 The return value of any function you put here should be one of
200 the objects in CHOICES, properly formatted with DISPLAY-FN (if
203 - To signal that your particular style of prompting is
204 unavailable at the moment, you can also have the function return
207 - To signal that the user quit the prompting process, you can
210 (signal 'quit \"user quit!\")."
211 :type '(repeat function)
214 (defcustom yas/indent-line 'auto
215 "Controls indenting applied to a recent snippet expansion.
217 The following values are possible:
219 - `fixed' Indent the snippet to the current column;
221 - `auto' Indent each line of the snippet with `indent-according-to-mode'
223 Every other value means don't apply any snippet-side indendation
224 after expansion (the manual per-line \"$>\" indentation still
226 :type '(choice (const :tag "Nothing" nothing)
227 (const :tag "Fixed" fixed)
228 (const :tag "Auto" auto))
231 (defcustom yas/also-auto-indent-first-line nil
232 "Non-nil means also auto indent first line according to mode.
234 Naturally this is only valid when `yas/indent-line' is `auto'"
238 (defcustom yas/snippet-revival t
239 "Non-nil means re-activate snippet fields after undo/redo."
243 (defcustom yas/trigger-key "TAB"
244 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
246 Value is a string that is converted to the internal Emacs key
247 representation using `read-kbd-macro'."
250 :set #'(lambda (symbol key)
251 (let ((old (and (boundp symbol)
252 (symbol-value symbol))))
253 (set-default symbol key)
254 ;; On very first loading of this defcustom,
255 ;; `yas/trigger-key' is *not* loaded.
256 (if (fboundp 'yas/trigger-key-reload)
257 (yas/trigger-key-reload old)))))
259 (defcustom yas/next-field-key '("TAB" "<tab>")
260 "The key to navigate to next field when a snippet is active.
262 Value is a string that is converted to the internal Emacs key
263 representation using `read-kbd-macro'.
265 Can also be a list of strings."
266 :type '(choice (string :tag "String")
267 (repeat :args (string) :tag "List of strings"))
269 :set #'(lambda (symbol val)
270 (set-default symbol val)
271 (if (fboundp 'yas/init-yas-in-snippet-keymap)
272 (yas/init-yas-in-snippet-keymap))))
275 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
276 "The key to navigate to previous field when a snippet is active.
278 Value is a string that is converted to the internal Emacs key
279 representation using `read-kbd-macro'.
281 Can also be a list of strings."
282 :type '(choice (string :tag "String")
283 (repeat :args (string) :tag "List of strings"))
285 :set #'(lambda (symbol val)
286 (set-default symbol val)
287 (if (fboundp 'yas/init-yas-in-snippet-keymap)
288 (yas/init-yas-in-snippet-keymap))))
290 (defcustom yas/skip-and-clear-key "C-d"
291 "The key to clear the currently active field.
293 Value is a string that is converted to the internal Emacs key
294 representation using `read-kbd-macro'.
296 Can also be a list of strings."
297 :type '(choice (string :tag "String")
298 (repeat :args (string) :tag "List of strings"))
300 :set #'(lambda (symbol val)
301 (set-default symbol val)
302 (if (fboundp 'yas/init-yas-in-snippet-keymap)
303 (yas/init-yas-in-snippet-keymap))))
305 (defcustom yas/triggers-in-field nil
306 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
308 Otherwise, `yas/next-field-key' just tries to move on to the next
313 (defcustom yas/fallback-behavior 'call-other-command
314 "How to act when `yas/trigger-key' does *not* expand a snippet.
316 - `call-other-command' means try to temporarily disable YASnippet
317 and call the next command bound to `yas/trigger-key'.
319 - nil or the symbol `return-nil' mean do nothing. (and
320 `yas/expand-returns' nil)
322 - A lisp form (apply COMMAND . ARGS) means interactively call
323 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
324 with ARGS as arguments."
325 :type '(choice (const :tag "Call previous command" call-other-command)
326 (const :tag "Do nothing" return-nil))
329 (defcustom yas/choose-keys-first nil
330 "If non-nil, prompt for snippet key first, then for template.
332 Otherwise prompts for all possible snippet names.
334 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
338 (defcustom yas/choose-tables-first nil
339 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
341 Otherwise, user chooses between the merging together of all
344 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
348 (defcustom yas/use-menu 'real-modes
349 "Display a YASnippet menu in the menu bar.
351 When non-nil, submenus for each snippet table will be listed
352 under the menu \"Yasnippet\".
354 - If set to `real-modes' only submenus whose name more or less
355 corresponds to a major mode are listed.
357 - If set to `abbreviate', only the current major-mode
358 menu and the modes set in `yas/mode-symbol' are listed.
360 Any other non-nil value, every submenu is listed."
361 :type '(choice (const :tag "Full" t)
362 (const :tag "Real modes only" real-modes)
363 (const :tag "Abbreviate" abbreviate))
366 (defcustom yas/trigger-symbol " =>"
367 "The text that will be used in menu to represent the trigger."
371 (defcustom yas/wrap-around-region nil
372 "If non-nil, snippet expansion wraps around selected region.
374 The wrapping occurs just before the snippet's exit marker. This
375 can be overriden on a per-snippet basis."
379 (defcustom yas/good-grace t
380 "If non-nil, don't raise errors in inline elisp evaluation.
382 An error string \"[yas] error\" is returned instead."
386 (defcustom yas/ignore-filenames-as-triggers nil
387 "If non-nil, don't derive tab triggers from filenames.
389 This means a snippet without a \"# key:'\ directive wont have a
394 (defcustom yas/visit-from-menu nil
395 "If non-nil visit snippets's files from menu, instead of expanding them.
397 This cafn only work when snippets are loaded from files."
401 (defface yas/field-highlight-face
402 '((((class color) (background light)) (:background "DarkSeaGreen1"))
403 (t (:background "DimGrey")))
404 "The face used to highlight the currently active field of a snippet"
407 (defface yas/field-debug-face
409 "The face used for debugging some overlays normally hidden"
413 ;;; User can also customize the next defvars
414 (defun yas/define-some-keys (keys keymap definition)
415 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
416 (let ((keys (or (and (listp keys) keys)
419 (define-key keymap (read-kbd-macro key) definition))))
422 (let ((map (make-sparse-keymap)))
423 (mapc #'(lambda (binding)
424 (yas/define-some-keys (car binding) map (cdr binding)))
425 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
426 (,yas/prev-field-key . yas/prev-field)
427 ("C-g" . yas/abort-snippet)
428 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
430 "The keymap active while a snippet expansion is in progress.")
432 (defvar yas/key-syntaxes (list "w" "w_" "w_.()" "^ ")
433 "A list of syntax of a key. This list is tried in the order
434 to try to find a key. For example, if the list is '(\"w\" \"w_\").
435 And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":
439 will first try \"bar\", if not found, then \"foo-bar\" is tried.")
441 (defvar yas/after-exit-snippet-hook
443 "Hooks to run after a snippet exited.
445 The hooks will be run in an environment where some variables bound to
448 `yas/snippet-beg' : The beginning of the region of the snippet.
450 `yas/snippet-end' : Similar to beg.
452 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
454 (defvar yas/before-expand-snippet-hook
456 "Hooks to run just before expanding a snippet.")
458 (defvar yas/buffer-local-condition
459 '(if (or (fourth (syntax-ppss))
460 (fifth (syntax-ppss)))
461 '(require-snippet-condition . force-in-comment)
463 "Snippet expanding condition.
465 This variable is a lisp form:
467 * If it evaluates to nil, no snippets can be expanded.
469 * If it evaluates to the a cons (require-snippet-condition
472 * Snippets bearing no \"# condition:\" directive are not
475 * Snippets bearing conditions that evaluate to nil (or
476 produce an error) won't be onsidered.
478 * If the snippet has a condition that evaluates to non-nil
481 * If REQUIREMENT is t, the snippet is considered
483 * If REQUIREMENT is `eq' RESULT, the snippet is
486 * Otherwise, the snippet is not considered.
488 * If it evaluates to the symbol 'always, all snippets are
489 considered for expansion, regardless of any conditions.
491 * If it evaluates to t or some other non-nil value
493 * Snippet bearing no conditions, or conditions that
494 evaluate to non-nil, are considered for expansion.
496 * Otherwise, the snippet is not considered.
498 Here's an example preventing snippets from being expanded from
499 inside comments, in `python-mode' only, with the exception of
500 snippets returning the symbol 'force-in-comment in their
503 (add-hook 'python-mode-hook
505 (setq yas/buffer-local-condition
506 '(if (python-in-string/comment)
507 '(require-snippet-condition . force-in-comment)
510 The default value is similar, it filters out potential snippet
511 expansions inside comments and string literals, unless the
512 snippet itself contains a condition that returns the symbol
513 `force-in-comment'.")
516 ;;; Internal variables
518 (defvar yas/version "0.7.0")
520 (defvar yas/menu-table (make-hash-table)
521 "A hash table of MAJOR-MODE symbols to menu keymaps.")
527 (defvar yas/known-modes
528 '(ruby-mode rst-mode markdown-mode)
529 "A list of mode which is well known but not part of emacs.")
531 (defvar yas/escaped-characters
533 "List of characters which *might* need to be escaped.")
535 (defconst yas/field-regexp
536 "${\\([0-9]+:\\)?\\([^}]*\\)}"
537 "A regexp to *almost* recognize a field.")
539 (defconst yas/multi-dollar-lisp-expression-regexp
540 "$+[ \t\n]*\\(([^)]*)\\)"
541 "A regexp to *almost* recognize a \"$(...)\" expression.")
543 (defconst yas/backquote-lisp-expression-regexp
545 "A regexp to recognize a \"`lisp-expression`\" expression." )
547 (defconst yas/transform-mirror-regexp
548 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
549 "A regexp to *almost* recognize a mirror with a transform.")
551 (defconst yas/simple-mirror-regexp
553 "A regexp to recognize a simple mirror.")
555 (defvar yas/snippet-id-seed 0
556 "Contains the next id for a snippet.")
558 (defun yas/snippet-next-id ()
559 (let ((id yas/snippet-id-seed))
560 (incf yas/snippet-id-seed)
566 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
567 (defvar last-buffer-undo-list nil)
569 (defvar yas/minor-mode-menu nil
570 "Holds the YASnippet menu")
572 (defun yas/init-minor-keymap ()
573 (let ((map (make-sparse-keymap)))
574 (easy-menu-define yas/minor-mode-menu
576 "Menu used when YAS/minor-mode is active."
579 ["Expand trigger" yas/expand
580 :help "Possibly expand tab trigger before point"]
581 ["Insert at point..." yas/insert-snippet
582 :help "Prompt for an expandable snippet and expand it at point"]
583 ["New snippet..." yas/new-snippet
584 :help "Create a new snippet in an appropriate directory"]
585 ["Visit snippet file..." yas/visit-snippet-file
586 :help "Prompt for an expandable snippet and find its file"]
587 ["Find snippets..." yas/find-snippets
588 :help "Invoke `find-file' in the appropriate snippet directory"]
590 ("Snippet menu behaviour"
591 ["Visit snippets" (setq yas/visit-from-menu t)
592 :help "Visit snippets from the menu"
593 :active t :style radio :selected yas/visit-from-menu]
594 ["Expand snippets" (setq yas/visit-from-menu nil)
595 :help "Expand snippets from the menu"
596 :active t :style radio :selected (not yas/visit-from-menu)]
598 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
599 :help "Show snippet submenus for modes that appear to be real major modes"
600 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
601 ["Show all modes" (setq yas/use-menu 't)
602 :help "Show one snippet submenu for each loaded table"
603 :active t :style radio :selected (eq yas/use-menu 't)]
604 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
605 :help "Show only snippet submenus for the current active modes"
606 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
608 ["Auto" (setq yas/indent-line 'auto)
609 :help "Indent each line of the snippet with `indent-according-to-mode'"
610 :active t :style radio :selected (eq yas/indent-line 'auto)]
611 ["Fixed" (setq yas/indent-line 'fixed)
612 :help "Indent the snippet to the current column"
613 :active t :style radio :selected (eq yas/indent-line 'fixed)]
614 ["None" (setq yas/indent-line 'none)
615 :help "Don't apply any particular snippet indentation after expansion"
616 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
618 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
619 (not yas/also-auto-indent-first-line))
620 :help "When auto-indenting also, auto indent the first line menu"
621 :active (eq yas/indent-line 'auto)
622 :style toggle :selected yas/also-auto-indent-first-line]
625 ["System X-widget" (setq yas/prompt-functions
627 (remove 'yas/x-prompt
628 yas/prompt-functions)))
629 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
630 :active t :style radio :selected (eq (car yas/prompt-functions)
632 ["Dropdown-list" (setq yas/prompt-functions
633 (cons 'yas/dropdown-prompt
634 (remove 'yas/dropdown-prompt
635 yas/prompt-functions)))
636 :help "Use a special dropdown list"
637 :active t :style radio :selected (eq (car yas/prompt-functions)
638 'yas/dropdown-prompt)]
639 ["Ido" (setq yas/prompt-functions
640 (cons 'yas/ido-prompt
641 (remove 'yas/ido-prompt
642 yas/prompt-functions)))
643 :help "Use an ido-style minibuffer prompt"
644 :active t :style radio :selected (eq (car yas/prompt-functions)
646 ["Completing read" (setq yas/prompt-functions
647 (cons 'yas/completing-prompt
648 (remove 'yas/completing-prompt-prompt
649 yas/prompt-functions)))
650 :help "Use a normal minibuffer prompt"
651 :active t :style radio :selected (eq (car yas/prompt-functions)
652 'yas/completing-prompt-prompt)]
655 ["Wrap region in exit marker"
656 (setq yas/wrap-around-region
657 (not yas/wrap-around-region))
658 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
659 :style toggle :selected yas/wrap-around-region]
660 ["Allow stacked expansions "
661 (setq yas/triggers-in-field
662 (not yas/triggers-in-field))
663 :help "If non-nil allow snippets to be triggered inside other snippet fields"
664 :style toggle :selected yas/triggers-in-field]
665 ["Revive snippets on undo "
666 (setq yas/snippet-revival
667 (not yas/snippet-revival))
668 :help "If non-nil allow snippets to become active again after undo"
669 :style toggle :selected yas/snippet-revival]
672 (not yas/good-grace))
673 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
674 :style toggle :selected yas/good-grace]
675 ["Ignore filenames as triggers"
676 (setq yas/ignore-filenames-as-triggers
677 (not yas/ignore-filenames-as-triggers))
678 :help "If non-nil don't derive tab triggers from filenames"
679 :style toggle :selected yas/ignore-filenames-as-triggers]
682 ["Load snippets..." yas/load-directory
683 :help "Load snippets from a specific directory"]
684 ["Reload everything" yas/reload-all
685 :help "Cleanup stuff, reload snippets, rebuild menus"]
687 :help "Display some information about YASsnippet"]))
688 ;; Now for the stuff that has direct keybindings
690 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
691 (define-key map "\C-c&\C-n" 'yas/new-snippet)
692 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
693 (define-key map "\C-c&\C-f" 'yas/find-snippets)
696 (defvar yas/minor-mode-map (yas/init-minor-keymap)
697 "The keymap used when `yas/minor-mode' is active.")
699 (defun yas/trigger-key-reload (&optional unbind-key)
700 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
702 With optional UNBIND-KEY, try to unbind that key from
703 `yas/minor-mode-map'."
704 (when (and unbind-key
706 (not (string= unbind-key "")))
707 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
708 (when (and yas/trigger-key
709 (stringp yas/trigger-key)
710 (not (string= yas/trigger-key "")))
711 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
713 (defvar yas/tables (make-hash-table)
714 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
716 (defvar yas/direct-keymaps (list)
717 "Keymap alist supporting direct snippet keybindings.
719 This variable is is placed `emulation-mode-map-alists'.
721 Its elements looks like (TABLE-NAME . KEYMAP) and are
722 calculated when loading snippets. TABLE-NAME is a variable
723 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
724 all defined direct keybindings to the command
725 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
727 (defun yas/direct-keymaps-reload ()
728 "Force reload the direct keybinding for active snippet tables."
730 (setq yas/direct-keymaps nil)
731 (maphash #'(lambda (name table)
732 (mapc #'(lambda (table)
733 (push (cons (intern (format "yas//direct-%s" name))
734 (yas/table-direct-keymap table))
736 (cons table (yas/table-get-all-parents table))))
739 (defun yas/direct-keymaps-set-vars ()
740 (let ((modes-to-activate (list major-mode))
742 (while (setq mode (get mode 'derived-mode-parent))
743 (push mode modes-to-activate))
744 (when yas/mode-symbol
745 (push yas/mode-symbol modes-to-activate))
746 (dolist (mode modes-to-activate)
747 (let ((name (intern (format "yas//direct-%s" mode))))
748 (set-default name nil)
749 (set (make-local-variable name) t)))))
751 (defvar yas/minor-mode-hook nil
752 "Hook run when yas/minor-mode is turned on")
755 (define-minor-mode yas/minor-mode
756 "Toggle YASnippet mode.
758 When YASnippet mode is enabled, the `tas/trigger-key' key expands
759 snippets of code depending on the mode.
761 With no argument, this command toggles the mode.
762 positive prefix argument turns on the mode.
763 Negative prefix argument turns off the mode.
765 You can customize the key through `yas/trigger-key'.
768 \\{yas/minor-mode-map}"
770 ;; The indicator for the mode line.
773 (cond (yas/minor-mode
774 ;; Reload the trigger key
776 (yas/trigger-key-reload)
777 ;; Load all snippets definitions unless we still don't have a
778 ;; root-directory or some snippets have already been loaded.
780 (unless (or (null yas/snippet-dirs)
781 (> (hash-table-count yas/tables) 0))
783 ;; Install the direct keymaps in `emulation-mode-map-alists'
784 ;; (we use `add-hook' even though it's not technically a hook,
785 ;; but it works). Then define variables named after modes to
786 ;; index `yas/direct-keymaps'.
788 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
789 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
791 ;; Uninstall the direct keymaps.
793 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
795 (defun yas/direct-keymaps-set-vars-runonce ()
796 (yas/direct-keymaps-set-vars)
797 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
799 (defvar yas/dont-activate #'(lambda ()
800 (and yas/snippet-dirs
801 (null (yas/get-snippet-tables))))
802 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
804 `yas/minor-mode-on' is usually called by `yas/global-mode' so
805 this effectively lets you define exceptions to the \"global\"
807 (make-variable-buffer-local 'yas/dont-activate)
809 (defun yas/minor-mode-on ()
810 "Turn on YASnippet minor mode.
812 Do this unless `yas/dont-activate' is t or the function
813 `yas/get-snippet-tables' (which see), returns an empty list."
815 (unless (or (and (functionp yas/dont-activate)
816 (funcall yas/dont-activate))
817 (and (not (functionp yas/dont-activate))
821 (defun yas/minor-mode-off ()
822 "Turn off YASnippet minor mode."
826 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
830 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
833 (defvar yas/font-lock-keywords
834 (append '(("^#.*$" . font-lock-comment-face))
835 lisp-font-lock-keywords
836 lisp-font-lock-keywords-1
837 lisp-font-lock-keywords-2
839 (0 font-lock-keyword-face)
840 (1 font-lock-string-face t))
842 (0 font-lock-keyword-face)
843 (1 font-lock-warning-face t))
844 ("${" font-lock-keyword-face)
845 ("$[0-9]+?" font-lock-preprocessor-face)
846 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
848 (0 font-lock-keyword-face)))))
850 (defun yas/init-major-keymap ()
851 (let ((map (make-sparse-keymap)))
852 (easy-menu-define nil
854 "Menu used when snippet-mode is active."
856 (mapcar #'(lambda (ent)
858 (define-key map (third ent) (second ent)))
859 (vector (first ent) (second ent) t))
861 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
862 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
865 (defvar snippet-mode-map
866 (yas/init-major-keymap)
867 "The keymap used when `snippet-mode' is active")
870 (define-derived-mode snippet-mode text-mode "Snippet"
871 "A mode for editing yasnippets"
872 (set-syntax-table (standard-syntax-table))
873 (setq font-lock-defaults '(yas/font-lock-keywords))
874 (set (make-local-variable 'require-final-newline) nil)
875 (use-local-map snippet-mode-map))
879 ;;; Internal structs for template management
881 (defstruct (yas/template (:constructor yas/make-blank-template))
882 "A template for a snippet."
895 (defun yas/populate-template (template &rest args)
896 "Helper function to populate a template with properties"
900 (position (intern (substring (symbol-name (car args)) 1))
901 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
903 (setq args (cddr args)))
906 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
907 "A table to store snippets for a particular mode.
909 Has the following fields:
913 A symbol name normally corresponding to a major mode, but can
914 also be a pseudo major-mode to be referenced in
915 `yas/mode-symbol', for example.
919 A hash table, known as the \"keyhash\" where key is a string or
920 a vector. In case of a string its the snippet trigger key,
921 whereas a vector means it's a direct keybinding. The value is
922 yet another hash of (NAME . TEMPLATE), known as the
923 \"namehash\", where NAME is the snippet name and TEMPLATE is a
924 `yas/template' object.
928 A list of tables considered parents of this table: i.e. when
929 searching for expansions they are searched as well.
931 `yas/table-direct-keymap'
933 A keymap for the snippets in this table that have direct
934 keybindings. This is kept in sync with the keyhash, i.e., all
935 the elements of the keyhash that are vectors appear here as
936 bindings to `yas/expand-from-keymap'.
940 A hash table mapping snippets uuid's to the same `yas/template'
941 objects. A snippet uuid defaults to the snippet's name.
944 (hash (make-hash-table :test 'equal))
945 (uuidhash (make-hash-table :test 'equal))
947 (direct-keymap (make-sparse-keymap)))
949 (defun yas/get-template-by-uuid (mode uuid)
950 "Find the snippet template in MODE by its UUID."
951 (let* ((table (gethash mode yas/tables mode)))
953 (gethash uuid (yas/table-uuidhash table)))))
955 ;; Apropos storing/updating, this works with two steps:
957 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
960 ;; 2. `yas/add-template' to add the mappings again:
962 ;; Create or index the entry in TABLES's `yas/table-hash'
963 ;; linking KEY to a namehash. That namehash links NAME to
964 ;; TEMPLATE, and is also created a new namehash inside that
967 (defun yas/remove-template-by-uuid (table uuid)
968 "Remove from TABLE a template identified by UUID."
969 (let ((template (gethash uuid (yas/table-uuidhash table))))
971 (let* ((name (yas/template-name template))
973 ;; Remove the name from each of the targeted namehashes
975 (maphash #'(lambda (k v)
976 (let ((template (gethash name v)))
978 (eq uuid (yas/template-uuid template)))
980 (when (zerop (hash-table-count v))
981 (push k empty-keys)))))
982 (yas/table-hash table))
983 ;; Remove the namehashed themselves if they've become empty
985 (dolist (key empty-keys)
986 (remhash key (yas/table-hash table)))
988 ;; Finally, remove the uuid from the uuidhash
990 (remhash uuid (yas/table-uuidhash table))))))
993 (defun yas/add-template (table template)
994 "Store in TABLE the snippet template TEMPLATE.
996 KEY can be a string (trigger key) of a vector (direct
998 (let ((name (yas/template-name template))
999 (key (yas/template-key template))
1000 (keybinding (yas/template-keybinding template))
1001 (menu-binding (car (yas/template-menu-binding-pair template))))
1002 (dolist (k (remove nil (list key keybinding)))
1006 (yas/table-hash table))
1008 (make-hash-table :test 'equal)
1009 (yas/table-hash table))))
1011 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1014 (setf (getf (cdr menu-binding) :keys)
1015 (or (and keybinding (key-description keybinding))
1016 (and key (concat key yas/trigger-symbol))))
1017 (setcar (cdr menu-binding)
1020 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1022 (defun yas/update-template (snippet-table template)
1023 "Add or update TEMPLATE in SNIPPET-TABLE"
1025 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1026 (yas/add-template snippet-table template))
1028 (defun yas/fetch (table key)
1029 "Fetch templates in TABLE by KEY.
1031 Return a list of cons (NAME . TEMPLATE) where NAME is a
1032 string and TEMPLATE is a `yas/template' structure."
1033 (let* ((keyhash (yas/table-hash table))
1034 (namehash (and keyhash (gethash key keyhash))))
1036 (yas/filter-templates-by-condition
1038 (maphash #'(lambda (k v)
1039 (push (cons k v) alist))
1044 ;;; Filtering/condition logic
1046 (defun yas/eval-condition (condition)
1053 (message (format "[yas] error in condition evaluation: %s"
1054 (error-message-string err)))
1058 (defun yas/filter-templates-by-condition (templates)
1059 "Filter the templates using the applicable condition.
1061 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1062 string and TEMPLATE is a `yas/template' structure.
1064 This function implements the rules described in
1065 `yas/buffer-local-condition'. See that variables documentation."
1066 (let ((requirement (yas/require-template-specific-condition-p)))
1067 (if (eq requirement 'always)
1069 (remove-if-not #'(lambda (pair)
1070 (yas/template-can-expand-p
1071 (yas/template-condition (cdr pair)) requirement))
1074 (defun yas/require-template-specific-condition-p ()
1075 "Decides if this buffer requests/requires snippet-specific
1076 conditions to filter out potential expansions."
1077 (if (eq 'always yas/buffer-local-condition)
1079 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1080 (yas/eval-condition yas/buffer-local-condition))
1081 yas/buffer-local-condition)))
1082 (when local-condition
1083 (if (eq local-condition t)
1085 (and (consp local-condition)
1086 (eq 'require-snippet-condition (car local-condition))
1087 (symbolp (cdr local-condition))
1088 (cdr local-condition)))))))
1090 (defun yas/template-can-expand-p (condition requirement)
1091 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1092 (let* ((result (or (null condition)
1093 (yas/eval-condition condition))))
1094 (cond ((eq requirement t)
1097 (eq requirement result)))))
1099 (defun yas/table-get-all-parents (table)
1100 "Returns a list of all parent tables of TABLE"
1101 (let ((parents (yas/table-parents table)))
1103 (append (copy-list parents)
1104 (mapcan #'yas/table-get-all-parents parents)))))
1106 (defun yas/table-templates (table)
1109 (maphash #'(lambda (key namehash)
1110 (maphash #'(lambda (name template)
1111 (push (cons name template) acc))
1113 (yas/table-hash table))
1114 (yas/filter-templates-by-condition acc))))
1116 (defun yas/current-key ()
1117 "Get the key under current position. A key is used to find
1118 the template of a snippet in the current snippet-table."
1119 (let ((start (point))
1121 (syntaxes yas/key-syntaxes)
1125 (while (and (not done) syntaxes)
1126 (setq syntax (car syntaxes))
1127 (setq syntaxes (cdr syntaxes))
1129 (skip-syntax-backward syntax)
1130 (setq start (point)))
1132 (mapcan #'(lambda (table)
1133 (yas/fetch table (buffer-substring-no-properties start end)))
1134 (yas/get-snippet-tables)))
1143 (defun yas/table-all-keys (table)
1146 (maphash #'(lambda (key templates)
1147 (when (yas/filter-templates-by-condition templates)
1149 (yas/table-hash table))
1153 ;;; Internal functions
1155 (defun yas/real-mode? (mode)
1156 "Try to find out if MODE is a real mode. The MODE bound to
1157 a function (like `c-mode') is considered real mode. Other well
1158 known mode like `ruby-mode' which is not part of Emacs might
1159 not bound to a function until it is loaded. So yasnippet keeps
1160 a list of modes like this to help the judgement."
1162 (find mode yas/known-modes)))
1164 (defun yas/eval-lisp (form)
1165 "Evaluate FORM and convert the result to string."
1166 (let ((retval (catch 'yas/exception
1172 (let ((result (eval form)))
1174 (format "%s" result))))))
1175 (error (if yas/good-grace
1176 (format "[yas] elisp error! %s" (error-message-string err))
1177 (error (format "[yas] elisp error: %s"
1178 (error-message-string err)))))))))
1179 (when (and (consp retval)
1180 (eq 'yas/exception (car retval)))
1181 (error (cdr retval)))
1184 (defun yas/eval-lisp-no-saves (form)
1187 (error (if yas/good-grace
1188 (format "[yas] elisp error! %s" (error-message-string err))
1189 (error (format "[yas] elisp error: %s"
1190 (error-message-string err)))))))
1192 (defun yas/read-lisp (string &optional nil-on-error)
1193 "Read STRING as a elisp expression and return it.
1195 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1196 return an expression that when evaluated will issue an error."
1199 (error (and (not nil-on-error)
1200 `(error (error-message-string err))))))
1202 (defun yas/read-keybinding (keybinding)
1203 "Read KEYBINDING as a snippet keybinding, return a vector."
1204 (when (and keybinding
1205 (not (string-match "keybinding" keybinding)))
1207 (let ((keybinding-string (or (and (string-match "\".*\"" keybinding)
1209 ;; "KEY-DESC" with quotes is deprecated..., but supported
1211 (read-kbd-macro keybinding-string 'need-vector))
1213 (message "[yas] warning: keybinding \"%s\" invalid for snippet \"%s\" since %s."
1214 keybinding name (error-message-string err))
1217 (defvar yas/mode-symbol nil
1218 "If non-nil, lookup snippets using this instead of `major-mode'.")
1219 (make-variable-buffer-local 'yas/mode-symbol)
1221 (defun yas/table-get-create (mode)
1222 "Get the snippet table corresponding to MODE.
1224 Optional DIRECTORY gets recorded as the default directory to
1225 search for snippet files if the retrieved/created table didn't
1226 already have such a property."
1227 (let ((table (gethash mode
1230 (setq table (yas/make-snippet-table (symbol-name mode)))
1231 (puthash mode table yas/tables)
1232 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1233 (yas/table-direct-keymap table)))
1236 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1237 "Get snippet tables for current buffer.
1239 Return a list of 'yas/table' objects indexed by mode.
1241 The modes are tried in this order: optional MODE-SYMBOL, then
1242 `yas/mode-symbol', then `major-mode' then, unless
1243 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1244 MODE-SYMBOL or `major-mode'.
1246 Guessing is done by looking up the MODE-SYMBOL's
1247 `derived-mode-parent' property, see also `derived-mode-p'."
1249 (mapcar #'(lambda (mode)
1250 (gethash mode yas/tables))
1251 (append (list mode-symbol)
1252 (if (listp yas/mode-symbol)
1254 (list yas/mode-symbol))
1256 (and (not dont-search-parents)
1257 (get (or mode-symbol major-mode)
1258 'derived-mode-parent))))))
1260 (dolist (table (remove nil mode-tables))
1261 (push table all-tables)
1262 (nconc all-tables (yas/table-get-all-parents table)))
1263 (remove-duplicates all-tables)))
1265 (defun yas/menu-keymap-get-create (table)
1266 "Get or create the main menu keymap correspondong to MODE.
1268 This may very well create a plethora of menu keymaps and arrange
1269 them in all `yas/menu-table'"
1270 (let* ((mode (intern (yas/table-name table)))
1271 (menu-keymap (or (gethash mode yas/menu-table)
1272 (puthash mode (make-sparse-keymap) yas/menu-table)))
1273 (parents (yas/table-parents table)))
1274 (mapc #'(lambda (parent)
1275 (define-key menu-keymap
1276 (vector (intern (concat "parent_shit_" (yas/table-name parent))))
1278 (concat "parent-table: "
1279 (yas/table-name parent))
1280 (yas/menu-keymap-get-create parent))))
1284 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1285 ;;; Template-related and snippet loading functions
1287 (defun yas/parse-template (&optional file group)
1288 "Parse the template in the current buffer.
1290 Optional FILE is the absolute file name of the file being
1293 Optional GROUP is the group where the template is to go,
1294 otherwise we attempt to calculate it from FILE.
1296 Return a snippet-definition, i.e. a list
1298 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1300 If the buffer contains a line of \"# --\" then the contents
1301 above this line are ignored. Variables can be set above this
1302 line through the syntax:
1306 Here's a list of currently recognized variables:
1317 #name: #include \"...\"
1322 (goto-char (point-min))
1323 (let* ((type 'snippet)
1325 (file-name-nondirectory file)))
1326 (key (unless yas/ignore-filenames-as-triggers
1328 (file-name-sans-extension name))))
1334 (yas/calculate-group file))))
1338 (if (re-search-forward "^# --\n" nil t)
1339 (progn (setq template
1340 (buffer-substring-no-properties (point)
1342 (setq bound (point))
1343 (goto-char (point-min))
1344 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1345 (when (string= "uuid" (match-string-no-properties 1))
1346 (setq uuid (match-string-no-properties 2)))
1347 (when (string= "type" (match-string-no-properties 1))
1348 (setq type (if (string= "command" (match-string-no-properties 2))
1351 (when (string= "key" (match-string-no-properties 1))
1352 (setq key (match-string-no-properties 2)))
1353 (when (string= "name" (match-string-no-properties 1))
1354 (setq name (match-string-no-properties 2)))
1355 (when (string= "condition" (match-string-no-properties 1))
1356 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1357 (when (string= "group" (match-string-no-properties 1))
1358 (message "[yas] Warning: the \"# group:\" is no longer supported!"))
1359 (when (string= "expand-env" (match-string-no-properties 1))
1360 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1362 (when (string= "binding" (match-string-no-properties 1))
1363 (setq binding (match-string-no-properties 2)))))
1365 (buffer-substring-no-properties (point-min) (point-max))))
1366 (when (eq type 'command)
1367 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1368 (list key template name condition group expand-env file binding uuid)))
1370 (defun yas/calculate-group (file)
1371 "Calculate the group for snippet file path FILE."
1372 (let* ((dominating-dir (locate-dominating-file file
1373 ".yas-make-groups"))
1374 (extra-path (and dominating-dir
1375 (replace-regexp-in-string (concat "^"
1376 (expand-file-name dominating-dir))
1378 (expand-file-name file))))
1379 (extra-dir (and extra-path
1380 (file-name-directory extra-path)))
1381 (group (and extra-dir
1382 (replace-regexp-in-string "/"
1384 (directory-file-name extra-dir)))))
1387 (defun yas/subdirs (directory &optional file?)
1388 "Return subdirs or files of DIRECTORY according to FILE?."
1389 (remove-if (lambda (file)
1390 (or (string-match "^\\."
1391 (file-name-nondirectory file))
1392 (string-match "^#.*#$"
1393 (file-name-nondirectory file))
1395 (file-name-nondirectory file))
1397 (file-directory-p file)
1398 (not (file-directory-p file)))))
1399 (directory-files directory t)))
1401 (defun yas/make-menu-binding (template)
1402 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1403 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1405 (defun yas/expand-or-visit-from-menu (mode uuid)
1406 (let* ((table (yas/table-get-create mode))
1407 (yas/current-template (and table
1408 (gethash uuid (yas/table-uuidhash table)))))
1409 (when yas/current-template
1410 (if yas/visit-from-menu
1411 (yas/visit-snippet-file-1 yas/current-template)
1412 (let ((where (if mark-active
1413 (cons (region-beginning) (region-end))
1414 (cons (point) (point)))))
1415 (yas/expand-snippet (yas/template-content yas/current-template)
1419 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1420 ;; Popping up for keys and templates
1422 (defun yas/prompt-for-template (templates &optional prompt)
1423 "Interactively choose a template from the list TEMPLATES.
1425 TEMPLATES is a list of `yas/template'."
1428 (sort templates #'(lambda (t1 t2)
1429 (< (length (yas/template-name t1))
1430 (length (yas/template-name t2))))))
1431 (if yas/x-pretty-prompt-templates
1432 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1433 (some #'(lambda (fn)
1434 (funcall fn (or prompt "Choose a snippet: ")
1436 #'yas/template-name))
1437 yas/prompt-functions))))
1439 (defun yas/prompt-for-keys (keys &optional prompt)
1440 "Interactively choose a template key from the list KEYS."
1442 (some #'(lambda (fn)
1443 (funcall fn (or prompt "Choose a snippet key: ") keys))
1444 yas/prompt-functions)))
1446 (defun yas/prompt-for-table (tables &optional prompt)
1448 (some #'(lambda (fn)
1449 (funcall fn (or prompt "Choose a snippet table: ")
1452 yas/prompt-functions)))
1454 (defun yas/x-prompt (prompt choices &optional display-fn)
1455 "Display choices in a x-window prompt."
1456 ;; FIXME: HACK: if we notice that one of the objects in choices is
1457 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1459 ;; This would be better implemented by passing CHOICES as a
1460 ;; strucutred tree rather than a list. Modifications would go as far
1461 ;; up as `yas/all-templates' I think.
1463 (when (and window-system choices)
1465 (let (menu d) ;; d for display
1467 (setq d (or (and display-fn (funcall display-fn c))
1470 (push (cons (concat " " d) c) menu))
1472 (push (car d) menu))))
1473 (setq menu (list prompt (push "title" menu)))
1474 (x-popup-menu (if (fboundp 'posn-at-point)
1475 (let ((x-y (posn-x-y (posn-at-point (point)))))
1476 (list (list (+ (car x-y) 10)
1484 (defvar yas/x-pretty-prompt-templates nil
1485 "If non-nil, attempt to prompt for templates like TextMate.")
1486 (defun yas/x-pretty-prompt-templates (prompt templates)
1487 "Display TEMPLATES, grouping neatly by table name."
1488 (let ((props (list))
1492 (dolist (tl templates)
1493 (push tl (getf props (intern (yas/table-name (yas/template-table tl))))))
1494 (setq more-than-one-table (> (length props) 2))
1495 (setq prefix (if more-than-one-table
1497 (dolist (thing props)
1498 (cond ((listp thing)
1499 (setq menu (nconc (mapcar #'(lambda (tl)
1500 (cons (concat prefix (yas/template-name tl))
1504 (more-than-one-table
1505 (push (symbol-name thing) menu))))
1506 (setq menu (nreverse menu))
1507 (x-popup-menu (if (fboundp 'posn-at-point)
1508 (let ((x-y (posn-x-y (posn-at-point (point)))))
1509 (list (list (+ (car x-y) 10)
1513 (list prompt (push "title" menu)))))
1515 (defun yas/ido-prompt (prompt choices &optional display-fn)
1516 (when (and (featurep 'ido)
1518 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1520 (eval-when-compile (require 'dropdown-list nil t))
1521 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1522 (when (featurep 'dropdown-list)
1523 (let (formatted-choices
1527 (dolist (choice choices)
1528 (setq d (or (and display-fn (funcall display-fn choice))
1531 (push d formatted-choices)
1532 (push choice filtered-choices)))
1533 (setq chosen (and formatted-choices
1534 (nth (dropdown-list formatted-choices)
1535 filtered-choices))))))
1537 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1538 (let (formatted-choices
1542 (completion-fn (or completion-fn
1543 #'completing-read)))
1544 (dolist (choice choices)
1545 (setq d (or (and display-fn (funcall display-fn choice))
1548 (push d formatted-choices)
1549 (push choice filtered-choices)))
1550 (setq chosen (and formatted-choices
1551 (funcall completion-fn prompt
1558 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1560 (defun yas/no-prompt (prompt choices &optional display-fn)
1563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1564 ;; Loading snippets from files
1566 (defun yas/load-directory-1 (directory &optional mode-sym parents)
1567 "Recursively load snippet templates from DIRECTORY."
1569 ;; Load .yas-setup.el files wherever we find them
1571 (let ((file (concat directory "/" ".yas-setup")))
1572 (when (or (file-readable-p (concat file ".el"))
1573 (file-readable-p (concat file ".elc")))
1578 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1579 (let* ((major-mode-and-parents (if mode-sym
1580 (cons mode-sym parents)
1581 (yas/compute-major-mode-and-parents (concat directory
1583 (yas/ignore-filenames-as-triggers
1584 (or yas/ignore-filenames-as-triggers
1585 (file-exists-p (concat directory "/"
1586 ".yas-ignore-filenames-as-triggers"))))
1588 ;; load the snippet files
1591 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1592 (when (file-readable-p file)
1593 (insert-file-contents file nil nil nil t)
1594 (push (yas/parse-template file)
1597 (yas/define-snippets (car major-mode-and-parents)
1599 (cdr major-mode-and-parents)))
1600 ;; now recurse to a lower level
1602 (dolist (subdir (yas/subdirs directory))
1603 (yas/load-directory-1 subdir
1604 (car major-mode-and-parents)
1605 (cdr major-mode-and-parents))))))
1607 (defun yas/load-directory (directory)
1608 "Load snippet definition from a directory hierarchy.
1610 Below the top-level directory, each directory is a mode
1611 name. And under each subdirectory, each file is a definition
1612 of a snippet. The file name is the trigger key and the
1613 content of the file is the template."
1614 (interactive "DSelect the root directory: ")
1615 (unless (file-directory-p directory)
1616 (error "Error %s not a directory" directory))
1617 (unless yas/snippet-dirs
1618 (setq yas/snippet-dirs directory))
1619 (dolist (dir (yas/subdirs directory))
1620 (yas/load-directory-1 dir))
1621 (when (interactive-p)
1622 (message "[yas] Loaded snippets from %s." directory)))
1624 (defun yas/load-snippet-dirs ()
1625 "Reload the directories listed in `yas/snippet-dirs' or
1626 prompt the user to select one."
1627 (if yas/snippet-dirs
1628 (if (listp yas/snippet-dirs)
1629 (dolist (directory (reverse yas/snippet-dirs))
1630 (yas/load-directory directory))
1631 (yas/load-directory yas/snippet-dirs))
1632 (call-interactively 'yas/load-directory)))
1634 (defun yas/reload-all (&optional reset-root-directory)
1635 "Reload all snippets and rebuild the YASnippet menu. "
1637 ;; Turn off global modes and minor modes, save their state though
1639 (let ((restore-global-mode (prog1 yas/global-mode
1640 (yas/global-mode -1)))
1641 (restore-minor-mode (prog1 yas/minor-mode
1642 (yas/minor-mode -1))))
1643 ;; Empty all snippet tables and all menu tables
1645 (setq yas/tables (make-hash-table))
1646 (setq yas/menu-table (make-hash-table))
1648 ;; Init the `yas/minor-mode-map', taking care not to break the
1651 (setf (cdr yas/minor-mode-map)
1652 (cdr (yas/init-minor-keymap)))
1654 (when reset-root-directory
1655 (setq yas/snippet-dirs nil))
1657 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1658 ;; the user to select one.
1660 (if yas/snippet-dirs
1661 (if (listp yas/snippet-dirs)
1662 (dolist (directory (reverse yas/snippet-dirs))
1663 (yas/load-directory directory))
1664 (yas/load-directory yas/snippet-dirs))
1665 (call-interactively 'yas/load-directory))
1666 ;; Reload the direct keybindings
1668 (yas/direct-keymaps-reload)
1669 ;; Restore the mode configuration
1671 (when restore-minor-mode
1673 (when restore-global-mode
1674 (yas/global-mode 1))
1676 (message "[yas] Reloading everything... Done.")))
1678 (defun yas/quote-string (string)
1679 "Escape and quote STRING.
1680 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1682 (replace-regexp-in-string "[\\\"]"
1687 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1688 ;;; Yasnippet Bundle
1690 (defun yas/initialize ()
1691 "For backward compatibility, enable `yas/minor-mode' globally"
1692 (yas/global-mode 1))
1694 (defun yas/compile-bundle
1695 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1696 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1698 YASNIPPET is the yasnippet.el file path.
1700 YASNIPPET-BUNDLE is the output file of the compile result.
1702 SNIPPET-ROOTS is a list of root directories that contains the
1703 snippets definition.
1705 CODE is the code to be placed at the end of the generated file
1706 and that can initialize the YASnippet bundle.
1708 Last optional argument DROPDOWN is the filename of the
1709 dropdown-list.el library.
1711 Here's the default value for all the parameters:
1713 (yas/compile-bundle \"yasnippet.el\"
1714 \"yasnippet-bundle.el\"
1716 \"(yas/initialize-bundle)
1718 (require 'yasnippet-bundle)`\"
1719 \"dropdown-list.el\")
1721 (interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "
1722 "\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))
1724 (let* ((yasnippet (or yasnippet
1726 (yasnippet-bundle (or yasnippet-bundle
1727 "./yasnippet-bundle.el"))
1728 (snippet-roots (or snippet-roots
1730 (dropdown (or dropdown
1731 "dropdown-list.el"))
1733 (condition-case err (read code) (error nil))
1735 (concat "(yas/initialize-bundle)"
1736 "\n;;;###autoload" ; break through so that won't
1737 "(require 'yasnippet-bundle)")))
1738 (dirs (or (and (listp snippet-roots) snippet-roots)
1739 (list snippet-roots)))
1740 (bundle-buffer nil))
1741 (with-temp-file yasnippet-bundle
1742 (insert ";;; yasnippet-bundle.el --- "
1743 "Yet another snippet extension (Auto compiled bundle)\n")
1744 (insert-file-contents yasnippet)
1745 (goto-char (point-max))
1748 (insert-file-contents dropdown))
1749 (goto-char (point-max))
1750 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1751 (insert ";;;; Auto-generated code ;;;;\n")
1752 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1753 (insert "(defun yas/initialize-bundle ()\n"
1754 " \"Initialize YASnippet and load snippets in the bundle.\"")
1755 (flet ((yas/define-snippets
1756 (mode snippets &optional parent-or-parents)
1757 (insert ";;; snippets for " (symbol-name mode) "\n")
1758 (let ((literal-snippets (list)))
1759 (dolist (snippet snippets)
1760 (let ((key (first snippet))
1761 (template-content (second snippet))
1762 (name (third snippet))
1763 (condition (fourth snippet))
1764 (group (fifth snippet))
1765 (expand-env (sixth snippet))
1766 (file nil) ;; (seventh snippet)) ;; omit on purpose
1767 (binding (eighth snippet))
1768 (uuid (ninth snippet)))
1779 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1782 (dolist (subdir (yas/subdirs dir))
1783 (let ((file (concat subdir "/.yas-setup.el")))
1784 (when (file-readable-p file)
1785 (insert ";; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")
1786 (goto-char (+ (point)
1787 (second (insert-file-contents file))))))
1788 (yas/load-directory-1 subdir nil))))
1790 (insert (pp-to-string `(yas/global-mode 1)))
1791 (insert ")\n\n" code "\n")
1793 ;; bundle-specific provide and value for yas/dont-activate
1794 (let ((bundle-feature-name (file-name-nondirectory
1795 (file-name-sans-extension
1796 yasnippet-bundle))))
1797 (insert (pp-to-string `(set-default 'yas/dont-activate
1799 (and (or yas/snippet-dirs
1800 (featurep ',(make-symbol bundle-feature-name)))
1801 (null (yas/get-snippet-tables)))))))
1802 (insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))
1805 (file-name-nondirectory yasnippet-bundle)
1808 (defun yas/compile-textmate-bundle ()
1810 (yas/compile-bundle "yasnippet.el"
1811 "./yasnippet-textmate-bundle.el"
1813 (concat "(yas/initialize-bundle)"
1814 "\n;;;###autoload" ; break through so that won't
1815 "(require 'yasnippet-textmate-bundle)")
1816 "dropdown-list.el"))
1818 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1819 ;;; Some user level functions
1824 (message (concat "yasnippet (version "
1826 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1828 (defun yas/define-snippets (mode snippets &optional parent-mode)
1829 "Define SNIPPETS for MODE.
1831 SNIPPETS is a list of snippet definitions, each taking the
1834 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1836 Within these, only KEY and TEMPLATE are actually mandatory.
1838 TEMPLATE might be a lisp form or a string, depending on whether
1839 this is a snippet or a snippet-command.
1841 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1842 been `yas/read-lisp'-ed and will eventually be
1845 The remaining elements are strings.
1847 FILE is probably of very little use if you're programatically
1850 UUID is the snippets \"unique-id\". Loading a second snippet file
1851 with the same uuid replaced the previous snippet.
1853 You can use `yas/parse-template' to return such lists based on
1854 the current buffers contents.
1856 Optional PARENT-MODE can be used to specify the parent tables of
1857 MODE. It can be a mode symbol of a list of mode symbols. It does
1858 not need to be a real mode."
1859 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1860 ;; for the list of snippet tables `parent-tables'.
1862 (let ((snippet-table (yas/table-get-create mode))
1863 (parent-tables (mapcar #'yas/table-get-create
1864 (if (listp parent-mode)
1866 (list parent-mode))))
1868 ;; X) Connect `snippet-table' with `parent-tables'.
1870 ;; TODO: this should be a remove-duplicates of the concatenation
1871 ;; of `snippet-table's existings parents with the new parents...
1873 (dolist (parent parent-tables)
1874 (unless (find parent (yas/table-parents snippet-table))
1876 (yas/table-parents snippet-table))))
1878 ;; X) The keymap created here here is the menu keymap, it is also
1879 ;; gotten/created according to MODE. Make a menu entry for
1883 (setq menu-keymap (yas/menu-keymap-get-create snippet-table))
1884 (define-key yas/minor-mode-menu (vector mode)
1885 `(menu-item ,(symbol-name mode) ,menu-keymap
1886 :visible (yas/show-menu-p ',mode))))
1887 ;; X) Now, iterate for evey snippet def list
1889 (dolist (snippet snippets)
1890 (yas/define-snippets-1 mode snippet snippet-table menu-keymap))))
1892 (defun yas/define-snippets-1 (mode snippet snippet-table menu-keymap)
1893 "Helper for `yas/define-snippets'."
1894 ;; X) Calculate some more defaults on the values returned by
1895 ;; `yas/parse-template'.
1897 (let* ((file (seventh snippet))
1898 (key (or (car snippet)
1899 (unless yas/ignore-filenames-as-triggers
1901 (file-name-sans-extension (file-name-nondirectory file))))))
1902 (name (or (third snippet)
1904 (file-name-directory file))))
1905 (condition (fourth snippet))
1906 (group (fifth snippet))
1907 (keybinding (yas/read-keybinding (eighth snippet)))
1908 (uuid (or (ninth snippet)
1910 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1911 (yas/make-blank-template))))
1913 ;; X) populate the template object
1915 (yas/populate-template template
1916 :table snippet-table
1918 :content (second snippet)
1920 :condition condition
1921 :expand-env (sixth snippet)
1922 :file (seventh snippet)
1923 :keybinding keybinding
1925 ;; X) setup the menu groups, reorganizing from group to group if
1928 (when (and yas/use-menu
1929 (not (cdr (yas/template-menu-binding-pair template))))
1930 (let ((group-keymap menu-keymap))
1931 ;; Delete this entry from another group if already exists
1932 ;; in some other group. An entry is considered as existing
1933 ;; in another group if its name string-matches.
1935 (yas/delete-from-keymap group-keymap name)
1937 ;; ... then add this entry to the correct group
1938 (when (and (not (null group))
1939 (not (string= "" group)))
1940 (dolist (subgroup (mapcar #'make-symbol
1941 (split-string group "\\.")))
1942 (let ((subgroup-keymap (lookup-key group-keymap
1943 (vector subgroup))))
1944 (when (null subgroup-keymap)
1945 (setq subgroup-keymap (make-sparse-keymap))
1946 (define-key group-keymap (vector subgroup)
1947 `(menu-item ,(symbol-name subgroup)
1949 (setq group-keymap subgroup-keymap))))
1950 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1951 (define-key group-keymap (vector (gensym)) (car menu-binding-pair)))))
1952 ;; X) Update this template in the appropriate table. This step
1953 ;; also will take care of adding the key indicators in the
1954 ;; templates menu entry, if any
1956 (yas/update-template snippet-table template)))
1958 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1959 "Get TEMPLATE's menu binding or assign it a new one."
1960 (or (yas/template-menu-binding-pair template)
1961 (let ((key (yas/template-key template))
1962 (keybinding (yas/template-keybinding template)))
1963 (setf (yas/template-menu-binding-pair template)
1964 (cons `(menu-item ,(or (yas/template-name template)
1965 (yas/template-uuid template))
1966 ,(yas/make-menu-binding template)
1970 (defun yas/show-menu-p (mode)
1971 (cond ((eq yas/use-menu 'abbreviate)
1973 (mapcar #'(lambda (table)
1974 (intern (yas/table-name table)))
1975 (yas/get-snippet-tables))))
1976 ((eq yas/use-menu 'real-modes)
1977 (yas/real-mode? mode))
1981 (defun yas/delete-from-keymap (keymap name)
1982 "Recursively delete items named NAME from KEYMAP and its submenus.
1984 Skip any submenus named \"parent mode\""
1985 ;; First of all, recursively enter submenus, i.e. the tree is
1986 ;; searched depth first so that stale submenus can be found in the
1989 (mapc #'(lambda (item)
1990 (when (and (keymapp (fourth item))
1991 (stringp (third item))
1992 (not (string-match "parent mode" (third item))))
1993 (yas/delete-from-keymap (fourth item) name)))
1996 (when (keymapp keymap)
1997 (let ((pos-in-keymap))
1998 (while (setq pos-in-keymap
1999 (position-if #'(lambda (item)
2002 ;; the menu item we want to delete
2003 (and (eq 'menu-item (second item))
2005 (and (string= (third item) name)))
2007 (and (keymapp (fourth item))
2008 (not (and (stringp (third item))
2009 (string-match "parent mode"
2011 (null (rest (fourth item)))))))
2013 (setf (nthcdr pos-in-keymap keymap)
2014 (nthcdr (+ 1 pos-in-keymap) keymap))))))
2016 (defun yas/define-menu (mode menu omit-items)
2017 (let* ((table (yas/table-get-create mode))
2018 (hash (yas/table-uuidhash table)))
2019 (yas/define-menu-1 table
2020 (yas/menu-keymap-get-create table)
2023 (dolist (uuid omit-items)
2024 (let ((template (or (gethash uuid hash)
2025 (yas/populate-template (puthash uuid
2026 (yas/make-blank-template)
2030 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
2032 (defun yas/define-menu-1 (table keymap menu uuidhash)
2033 (dolist (e (reverse menu))
2034 (cond ((eq (first e) 'yas/item)
2035 (let ((template (or (gethash (second e) uuidhash)
2036 (yas/populate-template (puthash (second e)
2037 (yas/make-blank-template)
2040 :uuid (second e)))))
2041 ;; (if (string= (second e) "944F1410-188C-4D70-8340-CECAA56FC7F2")
2043 (define-key keymap (vector (gensym))
2044 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2045 ;; ((eq (first e) 'yas/external-item)
2046 ;; (let ((template (some #'(lambda (table)
2047 ;; (gethash (second e) (yas/table-uuidhash table)))
2048 ;; (let (all-tables)
2049 ;; (maphash #'(lambda (k v)
2050 ;; (push v all-tables))
2054 ;; (define-key keymap (vector (gensym))
2055 ;; ;; '(menu-item "shit" 'ding)
2056 ;; (car (yas/snippet-menu-binding-pair-get-create template :stay)))
2057 ;; (message "[yas] external menu item %s not found anywhere!" (second e)))))
2058 ((eq (first e) 'yas/submenu)
2059 (let ((subkeymap (make-sparse-keymap)))
2060 (define-key keymap (vector (gensym))
2061 `(menu-item ,(second e) ,subkeymap))
2062 (yas/define-menu-1 table subkeymap (third e) uuidhash)))
2063 ((eq (first e) 'yas/separator)
2064 (define-key keymap (vector (gensym))
2065 '(menu-item "----")))
2067 (message "[yas] don't know anything about menu entry %s" (first e))))))
2069 (defun yas/define (mode key template &optional name condition group)
2070 "Define a snippet. Expanding KEY into TEMPLATE.
2072 NAME is a description to this template. Also update the menu if
2073 `yas/use-menu' is `t'. CONDITION is the condition attached to
2074 this snippet. If you attach a condition to a snippet, then it
2075 will only be expanded when the condition evaluated to non-nil."
2076 (yas/define-snippets mode
2077 (list (list key template name condition group))))
2079 (defun yas/hippie-try-expand (first-time?)
2080 "Integrate with hippie expand. Just put this function in
2081 `hippie-expand-try-functions-list'."
2082 (if (not first-time?)
2083 (let ((yas/fallback-behavior 'return-nil))
2089 ;;; Apropos condition-cache:
2094 (defvar yas/condition-cache-timestamp nil)
2095 (defmacro yas/define-condition-cache (func doc &rest body)
2096 "Define a function FUNC with doc DOC and body BODY, BODY is
2097 executed at most once every snippet expansion attempt, to check
2098 expansion conditions.
2100 It doesn't make any sense to call FUNC programatically."
2101 `(defun ,func () ,(if (and doc
2104 "\n\nFor use in snippets' conditions. Within each
2105 snippet-expansion routine like `yas/expand', computes actual
2106 value for the first time then always returns a cached value.")
2107 (setq body (cons doc body))
2109 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2110 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2111 (cdr timestamp-and-value)
2112 (let ((new-value (progn
2115 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2118 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2119 (defun yas/expand-from-trigger-key (&optional field)
2120 "Expand a snippet before point.
2122 If no snippet expansion is possible, fall back to the behaviour
2123 defined in `yas/fallback-behavior'.
2125 Optional argument FIELD is for non-interactive use and is an
2126 object satisfying `yas/field-p' to restrict the expansion to."
2128 (setq yas/condition-cache-timestamp (current-time))
2129 (multiple-value-bind (templates start end) (if field
2131 (narrow-to-region (yas/field-start field)
2132 (yas/field-end field))
2136 (yas/expand-or-prompt-for-template templates start end)
2137 (yas/fallback 'trigger-key))))
2139 (defun yas/expand-from-keymap ()
2140 "Directly expand some snippets, searching `yas/direct-keymaps'.
2142 If expansion fails, execute the previous binding for this key"
2144 (setq yas/condition-cache-timestamp (current-time))
2145 (let* ((vec (this-command-keys-vector))
2146 (templates (mapcan #'(lambda (table)
2147 (yas/fetch table vec))
2148 (yas/get-snippet-tables))))
2150 (yas/expand-or-prompt-for-template templates)
2151 (let ((yas/fallback-behavior 'call-other-command))
2154 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2155 "Expand one of TEMPLATES from START to END.
2157 Prompt the user if TEMPLATES has more than one element, else
2158 expand immediately. Common gateway for
2159 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2160 (let ((yas/current-template (or (and (rest templates) ;; more than one
2161 (yas/prompt-for-template (mapcar #'cdr templates)))
2163 (when yas/current-template
2164 (yas/expand-snippet (yas/template-content yas/current-template)
2167 (yas/template-expand-env yas/current-template)))))
2169 (defun yas/fallback (&optional from-trigger-key-p)
2170 "Fallback after expansion has failed.
2172 Common gateway for `yas/expand-from-trigger-key' and
2173 `yas/expand-from-keymap'."
2174 (cond ((eq yas/fallback-behavior 'return-nil)
2177 ((eq yas/fallback-behavior 'call-other-command)
2178 (let* ((yas/minor-mode nil)
2179 (yas/direct-keymaps nil)
2180 (keys-1 (this-command-keys-vector))
2181 (keys-2 (and yas/trigger-key
2183 (stringp yas/trigger-key)
2184 (read-kbd-macro yas/trigger-key)))
2185 (command-1 (and keys-1 (key-binding keys-1)))
2186 (command-2 (and keys-2 (key-binding keys-2)))
2187 ;; An (ugly) safety: prevents infinite recursion of
2188 ;; yas/expand* calls.
2189 (command (or (and (symbolp command-1)
2190 (not (string-match "yas/expand" (symbol-name command-1)))
2192 (and (symbolp command-2)
2194 (when (and (commandp command)
2195 (not (string-match "yas/expand" (symbol-name command))))
2196 (setq this-command command)
2197 (call-interactively command))))
2198 ((and (listp yas/fallback-behavior)
2199 (cdr yas/fallback-behavior)
2200 (eq 'apply (car yas/fallback-behavior)))
2201 (if (cddr yas/fallback-behavior)
2202 (apply (cadr yas/fallback-behavior)
2203 (cddr yas/fallback-behavior))
2204 (when (commandp (cadr yas/fallback-behavior))
2205 (setq this-command (cadr yas/fallback-behavior))
2206 (call-interactively (cadr yas/fallback-behavior)))))
2208 ;; also return nil if all the other fallbacks have failed
2213 ;;; Snippet development
2215 (defun yas/all-templates (tables)
2216 "Return all snippet tables applicable for the current buffer.
2218 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2219 `yas/buffer-local-condition'"
2220 (when yas/choose-tables-first
2221 (setq tables (list (yas/prompt-for-table tables))))
2223 (if yas/choose-keys-first
2224 (let ((key (yas/prompt-for-keys
2225 (mapcan #'yas/table-all-keys tables))))
2227 (mapcan #'(lambda (table)
2228 (yas/fetch table key))
2230 (remove-duplicates (mapcan #'yas/table-templates tables)
2233 (defun yas/insert-snippet (&optional no-condition)
2234 "Choose a snippet to expand, pop-up a list of choices according
2235 to `yas/prompt-function'.
2237 With prefix argument NO-CONDITION, bypass filtering of snippets
2240 (setq yas/condition-cache-timestamp (current-time))
2241 (let* ((yas/buffer-local-condition (or (and no-condition
2243 yas/buffer-local-condition))
2244 (templates (yas/all-templates (yas/get-snippet-tables)))
2245 (yas/current-template (and templates
2246 (or (and (rest templates) ;; more than one template for same key
2247 (yas/prompt-for-template templates))
2249 (where (if mark-active
2250 (cons (region-beginning) (region-end))
2251 (cons (point) (point)))))
2252 (if yas/current-template
2253 (yas/expand-snippet (yas/template-content yas/current-template)
2256 (yas/template-expand-env yas/current-template))
2257 (message "[yas] No snippets can be inserted here!"))))
2259 (defun yas/visit-snippet-file ()
2260 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2262 Only success if selected snippet was loaded from a file. Put the
2263 visited file in `snippet-mode'."
2265 (let* ((yas/buffer-local-condition 'always)
2266 (templates (yas/all-templates (yas/get-snippet-tables)))
2267 (template (and templates
2268 (or (and (rest templates) ;; more than one template for same key
2269 (yas/prompt-for-template templates
2270 "Choose a snippet template to edit: "))
2274 (yas/visit-snippet-file-1 template))))
2276 (defun yas/visit-snippet-file-1 (template)
2277 (let ((file (yas/template-file template)))
2278 (cond ((and file (file-readable-p file))
2279 (find-file-other-window file)
2281 (setq yas/editing-template template))
2283 (message "Original file %s no longer exists!" file))
2285 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2286 (let ((type 'snippet))
2287 (when (listp (yas/template-content template))
2288 (insert (format "# type: command\n"))
2289 (setq type 'command))
2290 (insert (format "# key: %s\n" (yas/template-key template)))
2291 (insert (format "# name: %s\n" (yas/template-name template)))
2292 (when (yas/template-keybinding template)
2293 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2294 (when (yas/template-expand-env template)
2295 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2296 (when (yas/template-condition template)
2297 (insert (format "# condition: %s\n" (yas/template-condition template))))
2299 (insert (if (eq type 'command)
2300 (pp-to-string (yas/template-content template))
2301 (yas/template-content template))))
2303 (setq yas/editing-template template)))))
2305 (defun yas/guess-snippet-directories-1 (table)
2306 "Guesses possible snippet subdirectories for TABLE."
2307 (cons (yas/table-name table)
2308 (mapcan #'(lambda (parent)
2309 (yas/guess-snippet-directories-1
2311 (yas/table-parents table))))
2313 (defun yas/guess-snippet-directories (&optional table)
2314 "Try to guess suitable directories based on the current active
2315 tables (or optional TABLE).
2317 Returns a a list of options alist TABLE -> DIRS where DIRS are
2318 all the possibly directories where snippets of table might be
2320 (let ((main-dir (replace-regexp-in-string
2322 (or (and (listp yas/snippet-dirs)
2323 (first yas/snippet-dirs))
2325 (setq yas/snippet-dirs "~/.emacs.d/snippets"))))
2326 (tables (or (and table
2328 (yas/get-snippet-tables))))
2329 ;; HACK! the snippet table created here is a dummy table that
2330 ;; holds the correct name so that `yas/make-directory-maybe' can
2331 ;; work. The real table, if it does not exist in
2332 ;; yas/tables will be created when the first snippet for
2333 ;; that mode is loaded.
2335 (unless (or table (gethash major-mode yas/tables))
2336 (setq tables (cons (yas/make-snippet-table (symbol-name major-mode))
2339 (mapcar #'(lambda (table)
2341 (mapcar #'(lambda (subdir)
2342 (concat main-dir "/" subdir))
2343 (yas/guess-snippet-directories-1 table))))
2346 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2347 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2348 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2349 (let ((candidate (first (cdr table-and-dirs))))
2350 (unless (file-writable-p (file-name-directory candidate))
2351 (error "[yas] %s is not writable." candidate))
2352 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2354 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2358 (or main-table-string
2360 (yas/table-name (car table-and-dirs))))
2362 (make-directory candidate 'also-make-parents)
2363 ;; create the .yas-parents file here...
2366 (defun yas/new-snippet (&optional choose-instead-of-guess)
2369 (let ((guessed-directories (yas/guess-snippet-directories)))
2371 (switch-to-buffer (format "*new snippet for %s*"
2372 (if guessed-directories
2373 (yas/table-name (car (first guessed-directories)))
2377 (setq yas/guessed-directories guessed-directories)
2378 (unless (and choose-instead-of-guess
2379 (not (y-or-n-p "Insert a snippet with useful headers? ")))
2380 (yas/expand-snippet "\
2381 # -*- mode: snippet -*-
2384 # binding: ${4:direct-keybinding}}${5:
2385 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2390 (defun yas/find-snippets (&optional same-window )
2391 "Look for user snippets in guessed current mode's directory.
2393 Calls `find-file' interactively in the guessed directory.
2395 With prefix arg SAME-WINDOW opens the buffer in the same window.
2397 Because snippets can be loaded from many different locations,
2398 this has to guess the correct directory using
2399 `yas/guess-snippet-directories', which returns a list of
2402 If any one of these exists, it is taken and `find-file' is called
2403 there, otherwise, proposes to create the first option returned by
2404 `yas/guess-snippet-directories'."
2406 (let* ((guessed-directories (yas/guess-snippet-directories))
2409 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2411 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2412 (mapcar #'(lambda (table-and-dirs)
2413 (yas/table-name (car table-and-dirs)))
2414 (rest guessed-directories))))
2415 (setq chosen (some #'yas/make-directory-maybe
2416 (rest guessed-directories)))))
2418 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2419 (setq chosen (if (listp yas/snippet-dirs)
2420 (first yas/snippet-dirs)
2421 yas/snippet-dirs))))
2423 (let ((default-directory chosen))
2424 (setq buffer (call-interactively (if same-window
2426 'find-file-other-window)))
2430 (when (eq major-mode 'fundamental-mode)
2432 (message "Could not guess snippet dir!"))))
2434 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)
2435 (let* ((file-dir (and file
2436 (directory-file-name (or (locate-dominating-file file ".yas-make-groups")
2437 (directory-file-name (file-name-directory file))))))
2438 (parents-file-name (concat file-dir "/.yas-parents"))
2439 (major-mode-name (and file-dir
2440 (file-name-nondirectory file-dir)))
2441 (major-mode-sym (or (and major-mode-name
2442 (intern major-mode-name))
2443 (when prompt-if-failed
2444 (read-from-minibuffer
2445 "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
2446 (parents (when (file-readable-p parents-file-name)
2450 (insert-file-contents parents-file-name)
2451 (buffer-substring-no-properties (point-min)
2453 (when major-mode-sym
2454 (cons major-mode-sym parents))))
2456 (defvar yas/editing-template nil
2457 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2459 (defvar yas/current-template nil
2460 "Holds the current template being expanded into a snippet.")
2462 (defvar yas/guessed-directories nil
2463 "Supporting variable for `yas/load-snippet-buffer' and `yas/new-snippet'")
2465 (defun yas/load-snippet-buffer (&optional kill)
2466 "Parse and load current buffer's snippet definition.
2468 With optional prefix argument KILL quit the window and buffer."
2471 ;; X) Option 1: We have `yas/editing-template', this buffer's
2472 ;; content comes from a template which is already loaded and
2473 ;; neatly positioned,...
2475 ((and (boundp 'yas/editing-template)
2476 yas/editing-template
2477 (yas/template-p yas/editing-template))
2479 (let ((parsed (yas/parse-template (yas/template-file yas/editing-template))))
2480 ;; ... just change its template, expand-env, condition, key,
2481 ;; keybinding and name. The group cannot be changed.
2482 (yas/populate-template yas/editing-template
2483 :content (second parsed)
2485 :name (third parsed)
2486 :condition (fourth parsed)
2487 :expand-env (sixth parsed)
2488 :keybinding (yas/read-keybinding (eighth parsed)))
2489 (yas/update-template (yas/template-table yas/editing-template)
2490 yas/editing-template))
2491 ;; Now, prompt for new file creation much like
2492 ;; `yas/new-snippet' if one of the following is true:
2494 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2495 ;; match this template's file (i.e. this is a library snippet, not
2498 ;; 2) yas/editing-template comes from a file that we cannot write to...
2500 (when (or (and (listp yas/snippet-dirs)
2501 (second yas/snippet-dirs)
2502 (not (string-match (expand-file-name (first yas/snippet-dirs))
2503 (yas/template-file yas/editing-template))))
2504 (and (yas/template-file yas/editing-template)
2505 (not (file-writable-p (yas/template-file yas/editing-template))))
2506 (not (yas/template-file yas/editing-template)))
2507 (when (y-or-n-p "[yas] Also save snippet buffer to new file? ")
2508 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2510 (yas/make-directory-maybe option))))
2512 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2513 (file-name-nondirectory (yas/template-file yas/editing-template)))
2514 (yas/template-name yas/editing-template))))
2515 (write-file (concat chosen "/"
2516 (read-from-minibuffer (format "File name to create in %s? " chosen)
2517 default-file-name)))
2518 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2521 (message "[yas] Snippet \"%s\" loaded for %s."
2522 (yas/template-name yas/editing-template)
2523 (yas/table-name (yas/template-table yas/editing-template))))
2524 (;; X) Option 2: We have a file name, consider this a brand new
2525 ;; snippet and calculate name, groups, etc from the current
2526 ;; file-name and buffer content
2529 (let ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name)))
2530 (if major-mode-and-parent
2531 (let* ((yas/ignore-filenames-as-triggers (or yas/ignore-filenames-as-triggers
2532 (locate-dominating-file buffer-file-name ".yas-ignore-filenames-as-triggers")))
2533 (parsed (yas/parse-template buffer-file-name))
2537 (yas/define-snippets (car major-mode-and-parent)
2539 (cdr major-mode-and-parent)))
2540 (when (and (buffer-modified-p)
2541 (y-or-n-p "Also save snippet buffer? "))
2545 (message "[yas] Snippet \"%s\" loaded for %s."
2547 (car major-mode-and-parent)))
2548 (message (format "[yas] Unknown major mode for snippet at %s" buffer-file-name)))))
2550 ;; X) Option 3: We have `yas/guessed-directories', this
2551 ;; buffer's content comes from `yas/new-snippet' call. Prompt
2552 ;; user for dir and name in guessed dirs, then call
2553 ;; `yas/load-snippet-buffer' (ourselves) again to load the
2554 ;; snippet based on the file-name.
2556 ((and (boundp 'yas/guessed-directories)
2557 yas/guessed-directories)
2558 (let* ((yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2559 (guessed-directories yas/guessed-directories)
2560 (option (or (and (not (y-or-n-p "Let yasnippet guess tables? "))
2562 (yas/guess-snippet-directories
2563 (some #'(lambda (fn)
2564 (funcall fn "Choose any snippet table: "
2566 (maphash #'(lambda (k v)
2571 yas/prompt-functions))))
2572 (and (second guessed-directories)
2573 (some #'(lambda (fn)
2574 (funcall fn "Choose from guessed list of tables: "
2577 (yas/table-name (car option)))))
2578 yas/prompt-functions))
2579 (first guessed-directories)))
2581 (setq chosen (yas/make-directory-maybe option))
2584 (when (y-or-n-p "Having trouble... use snippet root dir? ")
2585 (setq chosen (if (listp yas/snippet-dirs)
2586 (first yas/snippet-dirs)
2587 yas/snippet-dirs))))
2589 (let ((default-directory chosen))
2590 (call-interactively 'write-file))
2591 (setq yas/guessed-directories nil)
2592 (setq yas/editing-template nil)
2593 (yas/load-snippet-buffer))))))
2596 (defun yas/tryout-snippet (&optional debug)
2597 "Test current buffers's snippet template in other buffer."
2599 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2600 (parsed (yas/parse-template))
2601 (test-mode (or (and (car major-mode-and-parent)
2602 (fboundp (car major-mode-and-parent))
2603 (car major-mode-and-parent))
2604 (and yas/guessed-directories
2605 (intern (yas/table-name (car (first yas/guessed-directories)))))
2606 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2607 (yas/current-template
2610 (yas/populate-template (yas/make-blank-template)
2611 :table nil ;; no tables for ephemeral snippets
2613 :content (second parsed)
2614 :name (third parsed)
2615 :expand-env (sixth parsed)))))
2616 (cond (yas/current-template
2617 (let ((buffer-name (format "*YAS TEST: %s*" (yas/template-name yas/current-template))))
2618 (set-buffer (switch-to-buffer buffer-name))
2620 (setq buffer-undo-list nil)
2621 (condition-case nil (funcall test-mode) (error nil))
2622 (yas/expand-snippet (yas/template-content yas/current-template)
2625 (yas/template-expand-env yas/current-template))
2627 (require 'yasnippet-debug nil t))
2628 (add-hook 'post-command-hook 'yas/debug-snippet-vars 't 'local))))
2630 (message "[yas] Cannot test snippet for unknown major mode")))))
2632 (defun yas/describe-tables (&optional choose)
2633 "Display snippets for each table."
2635 (let* ((by-name-hash (and choose
2636 (y-or-n-p "Show by namehash? ")))
2637 (buffer (get-buffer-create "*YASnippet tables*"))
2638 (active-tables (yas/get-snippet-tables))
2639 (remain-tables (let ((all))
2640 (maphash #'(lambda (k v)
2641 (unless (find v active-tables)
2645 (table-lists (list active-tables remain-tables))
2646 (original-buffer (current-buffer))
2648 (yas/condition-cache-timestamp (current-time)))
2649 (with-current-buffer buffer
2650 (let ((buffer-read-only nil))
2652 (cond ((not by-name-hash)
2653 (insert "YASnippet tables by UUID: \n")
2654 (while (and table-lists
2656 (dolist (table (car table-lists))
2657 (insert (format "\nSnippet table `%s'"
2658 (yas/table-name table)))
2659 (if (yas/table-parents table)
2660 (insert (format " parents: %s\n"
2661 (mapcar #'yas/table-name
2662 (yas/table-parents table))))
2664 (let ((always (cons "(a)" (list)))
2665 (active (cons "(y)" (list)))
2666 (sleeping (cons "(n)" (list))))
2667 (maphash #'(lambda (k v)
2668 (let ((condition (yas/template-condition v)))
2670 (with-current-buffer original-buffer
2671 (if (yas/eval-condition condition)
2672 (push v (cdr active))
2673 (push v (cdr sleeping))))
2674 (push v (cdr always)))))
2675 (yas/table-uuidhash table))
2676 (dolist (type-and-templates (list always active sleeping))
2677 (dolist (p (cdr type-and-templates))
2678 (let ((name (yas/template-name p)))
2679 (insert (propertize (format "%s \\\\snippet `%s'" (car type-and-templates) name) 'yasnippet p))
2680 (insert (make-string (max (- 50 (length name))
2682 (when (yas/template-key p)
2683 (insert (format "key \"%s\" " (yas/template-key p))))
2684 (when (yas/template-keybinding p)
2685 (insert (format "bound to %s " (key-description (yas/template-keybinding p)))))
2687 (setq table-lists (cdr table-lists))
2689 (yas/create-snippet-xrefs)
2690 (display-buffer buffer)
2691 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2692 (yas/create-snippet-xrefs)
2695 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2696 (dolist (table (append active-tables remain-tables))
2697 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2699 (maphash #'(lambda (k v)
2701 (yas/table-hash table))
2703 (insert (format " key %s maps snippets: %s\n" key
2705 (maphash #'(lambda (k v)
2707 (gethash key (yas/table-hash table)))
2709 (display-buffer buffer)
2710 (with-current-buffer buffer
2711 (goto-char (point-min)))))
2714 ;;; User convenience functions, for using in snippet definitions
2716 (defvar yas/modified-p nil
2717 "Non-nil if field has been modified by user or transformation.")
2719 (defvar yas/moving-away-p nil
2720 "Non-nil if user is about to exit field.")
2722 (defvar yas/text nil
2723 "Contains current field text.")
2725 (defun yas/substr (str pattern &optional subexp)
2726 "Search PATTERN in STR and return SUBEXPth match.
2728 If found, the content of subexp group SUBEXP (default 0) is
2729 returned, or else the original STR will be returned."
2730 (let ((grp (or subexp 0)))
2732 (if (string-match pattern str)
2733 (match-string-no-properties grp str)
2736 (defun yas/choose-value (possibilities)
2737 "Prompt for a string in the list POSSIBILITIES and return it."
2738 (unless (or yas/moving-away-p
2740 (some #'(lambda (fn)
2741 (funcall fn "Choose: " possibilities))
2742 yas/prompt-functions)))
2744 (defun yas/key-to-value (alist)
2745 "Prompt for a string in the list POSSIBILITIES and return it."
2746 (unless (or yas/moving-away-p
2748 (let ((key (read-key-sequence "")))
2750 (or (cdr (find key alist :key #'car :test #'string=))
2753 (defun yas/throw (text)
2754 "Throw a yas/exception with TEXT as the reason."
2755 (throw 'yas/exception (cons 'yas/exception text)))
2757 (defun yas/verify-value (possibilities)
2758 "Verify that the current field value is in POSSIBILITIES
2760 Otherwise throw exception."
2761 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2762 (yas/throw (format "[yas] field only allows %s" possibilities))))
2764 (defun yas/field-value (number)
2765 "A primary field transformation..."
2766 (let* ((snippet (car (yas/snippets-at-point)))
2768 (yas/snippet-find-field snippet number))))
2770 (yas/field-text-for-display field))))
2774 (not (string= "" yas/text)))
2777 (defun yas/get-field-once (number &optional transform-fn)
2778 (unless yas/modified-p
2780 (funcall transform-fn (yas/field-value number))
2781 (yas/field-value number))))
2783 (defun yas/default-from-field (number)
2784 (unless yas/modified-p
2785 (yas/field-value number)))
2787 (defun yas/inside-string ()
2788 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2790 (defun yas/unimplemented ()
2791 (if yas/current-template
2792 (if (y-or-n-p "This snippet is unimplemented. Visit the snippet definition? ")
2793 (yas/visit-snippet-file-1 yas/current-template))
2794 (message "No implementation.")))
2797 ;;; Snippet expansion and field management
2799 (defvar yas/active-field-overlay nil
2800 "Overlays the currently active field.")
2802 (defvar yas/field-protection-overlays nil
2803 "Two overlays protect the current active field ")
2805 (defconst yas/prefix nil
2806 "A prefix argument for expansion direct from keybindings")
2808 (defvar yas/deleted-text nil
2809 "The text deleted in the last snippet expansion.")
2811 (defvar yas/selected-text nil
2812 "The selected region deleted on the last snippet expansion.")
2814 (defvar yas/start-column nil
2815 "The column where the snippet expansion started.")
2817 (make-variable-buffer-local 'yas/active-field-overlay)
2818 (make-variable-buffer-local 'yas/field-protection-overlays)
2819 (make-variable-buffer-local 'yas/deleted-text)
2821 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2827 (id (yas/snippet-next-id) :read-only t)
2828 (control-overlay nil)
2830 ;; stacked expansion: the `previous-active-field' slot saves the
2831 ;; active field where the child expansion took place
2832 previous-active-field
2835 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2845 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2852 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2856 (defun yas/apply-transform (field-or-mirror field)
2857 "Calculate the value of the field/mirror. If there's a transform
2858 for this field, apply it. Otherwise, returned nil."
2859 (let* ((yas/text (yas/field-text-for-display field))
2861 (yas/modified-p (yas/field-modified-p field))
2862 (yas/moving-away-p nil)
2863 (transform (if (yas/mirror-p field-or-mirror)
2864 (yas/mirror-transform field-or-mirror)
2865 (yas/field-transform field-or-mirror)))
2866 (start-point (if (yas/mirror-p field-or-mirror)
2867 (yas/mirror-start field-or-mirror)
2868 (yas/field-start field-or-mirror)))
2869 (transformed (and transform
2871 (goto-char start-point)
2872 (let ((ret (yas/eval-lisp transform)))
2876 (defsubst yas/replace-all (from to &optional text)
2877 "Replace all occurance from FROM to TO.
2879 With optional string TEXT do it in that string."
2881 (replace-regexp-in-string (regexp-quote from) to text t t)
2882 (goto-char (point-min))
2883 (while (search-forward from nil t)
2884 (replace-match to t t text))))
2886 (defun yas/snippet-find-field (snippet number)
2887 (find-if #'(lambda (field)
2888 (eq number (yas/field-number field)))
2889 (yas/snippet-fields snippet)))
2891 (defun yas/snippet-sort-fields (snippet)
2892 "Sort the fields of SNIPPET in navigation order."
2893 (setf (yas/snippet-fields snippet)
2894 (sort (yas/snippet-fields snippet)
2895 #'yas/snippet-field-compare)))
2897 (defun yas/snippet-field-compare (field1 field2)
2898 "Compare two fields. The field with a number is sorted first.
2899 If they both have a number, compare through the number. If neither
2900 have, compare through the field's start point"
2901 (let ((n1 (yas/field-number field1))
2902 (n2 (yas/field-number field2)))
2905 (or (zerop n2) (and (not (zerop n1))
2910 (< (yas/field-start field1)
2911 (yas/field-start field2))))))
2913 (defun yas/field-probably-deleted-p (snippet field)
2914 "Guess if SNIPPET's FIELD should be skipped."
2915 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2916 (or (yas/field-parent-field field)
2917 (and (eq field (car (last (yas/snippet-fields snippet))))
2918 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))))
2920 (defun yas/snippets-at-point (&optional all-snippets)
2921 "Return a sorted list of snippets at point, most recently
2924 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2925 (overlay-get ov 'yas/snippet))
2927 (overlays-in (point-min) (point-max))
2928 (overlays-at (point))))))
2930 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2932 (defun yas/next-field-or-maybe-expand ()
2933 "Try to expand a snippet at a key before point, otherwise
2934 delegate to `yas/next-field'."
2936 (if yas/triggers-in-field
2937 (let ((yas/fallback-behavior 'return-nil)
2938 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2940 (unless (yas/expand-from-trigger-key active-field)
2944 (defun yas/next-field (&optional arg)
2945 "Navigate to next field. If there's none, exit the snippet."
2949 (snippet (first (yas/snippets-at-point)))
2950 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2951 (live-fields (remove-if #'(lambda (field)
2952 (and (not (eq field active-field))
2953 (yas/field-probably-deleted-p snippet field)))
2954 (yas/snippet-fields snippet)))
2955 (active-field-pos (position active-field live-fields))
2956 (target-pos (and active-field-pos (+ arg active-field-pos)))
2957 (target-field (nth target-pos live-fields)))
2958 ;; First check if we're moving out of a field with a transform
2960 (when (and active-field
2961 (yas/field-transform active-field))
2962 (let* ((yas/moving-away-p t)
2963 (yas/text (yas/field-text-for-display active-field))
2965 (yas/modified-p (yas/field-modified-p active-field)))
2966 ;; primary field transform: exit call to field-transform
2967 (yas/eval-lisp (yas/field-transform active-field))))
2968 ;; Now actually move...
2969 (cond ((>= target-pos (length live-fields))
2970 (yas/exit-snippet snippet))
2972 (yas/move-to-field snippet target-field))
2976 (defun yas/place-overlays (snippet field)
2977 "Correctly place overlays for SNIPPET's FIELD"
2978 (yas/make-move-field-protection-overlays snippet field)
2979 (yas/make-move-active-field-overlay snippet field))
2981 (defun yas/move-to-field (snippet field)
2982 "Update SNIPPET to move to field FIELD.
2984 Also create some protection overlays"
2985 (goto-char (yas/field-start field))
2986 (setf (yas/snippet-active-field snippet) field)
2987 (yas/place-overlays snippet field)
2988 (overlay-put yas/active-field-overlay 'yas/field field)
2989 ;; primary field transform: first call to snippet transform
2990 (unless (yas/field-modified-p field)
2991 (if (yas/field-update-display field snippet)
2992 (let ((inhibit-modification-hooks t))
2993 (yas/update-mirrors snippet))
2994 (setf (yas/field-modified-p field) nil))))
2996 (defun yas/prev-field ()
2997 "Navigate to prev field. If there's none, exit the snippet."
2999 (yas/next-field -1))
3001 (defun yas/abort-snippet (&optional snippet)
3003 (let ((snippet (or snippet
3004 (car (yas/snippets-at-point)))))
3006 (setf (yas/snippet-force-exit snippet) t))))
3008 (defun yas/exit-snippet (snippet)
3009 "Goto exit-marker of SNIPPET."
3011 (setf (yas/snippet-force-exit snippet) t)
3012 (goto-char (if (yas/snippet-exit snippet)
3013 (yas/exit-marker (yas/snippet-exit snippet))
3014 (overlay-end (yas/snippet-control-overlay snippet)))))
3016 (defun yas/exit-all-snippets ()
3017 "Exit all snippets."
3019 (mapc #'(lambda (snippet)
3020 (yas/exit-snippet snippet)
3021 (yas/check-commit-snippet))
3022 (yas/snippets-at-point)))
3025 ;;; Some low level snippet-routines
3027 (defun yas/commit-snippet (snippet &optional no-hooks)
3028 "Commit SNIPPET, but leave point as it is. This renders the
3029 snippet as ordinary text.
3031 Return a buffer position where the point should be placed if
3032 exiting the snippet.
3034 NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
3036 (let ((control-overlay (yas/snippet-control-overlay snippet))
3040 ;; Save the end of the moribund snippet in case we need to revive it
3041 ;; its original expansion.
3043 (when (and control-overlay
3044 (overlay-buffer control-overlay))
3045 (setq yas/snippet-beg (overlay-start control-overlay))
3046 (setq yas/snippet-end (overlay-end control-overlay))
3047 (delete-overlay control-overlay))
3049 (let ((inhibit-modification-hooks t))
3050 (when yas/active-field-overlay
3051 (delete-overlay yas/active-field-overlay))
3052 (when yas/field-protection-overlays
3053 (mapc #'delete-overlay yas/field-protection-overlays)))
3055 ;; stacked expansion: if the original expansion took place from a
3056 ;; field, make sure we advance it here at least to
3057 ;; `yas/snippet-end'...
3059 (let ((previous-field (yas/snippet-previous-active-field snippet)))
3060 (when (and yas/snippet-end previous-field)
3061 (yas/advance-end-maybe previous-field yas/snippet-end)))
3063 ;; Convert all markers to points,
3065 (yas/markers-to-points snippet)
3067 ;; Take care of snippet revival
3069 (if yas/snippet-revival
3070 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
3072 ;; Dismember the snippet... this is useful if we get called
3073 ;; again from `yas/take-care-of-redo'....
3074 (setf (yas/snippet-fields snippet) nil))
3076 ;; XXX: `yas/after-exit-snippet-hook' should be run with
3077 ;; `yas/snippet-beg' and `yas/snippet-end' bound. That might not
3078 ;; be the case if the main overlay had somehow already
3079 ;; disappeared, which sometimes happens when the snippet's messed
3082 (unless no-hooks (run-hooks 'yas/after-exit-snippet-hook)))
3084 (message "[yas] snippet exited."))
3086 (defun yas/check-commit-snippet ()
3087 "Checks if point exited the currently active field of the
3088 snippet, if so cleans up the whole snippet up."
3089 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3090 (snippets-left snippets))
3091 (dolist (snippet snippets)
3092 (let ((active-field (yas/snippet-active-field snippet)))
3093 (cond ((or (prog1 (yas/snippet-force-exit snippet)
3094 (setf (yas/snippet-force-exit snippet) nil))
3095 (not (and active-field (yas/field-contains-point-p active-field))))
3096 (setq snippets-left (delete snippet snippets-left))
3097 (yas/commit-snippet snippet snippets-left))
3099 (or (not yas/active-field-overlay)
3100 (not (overlay-buffer yas/active-field-overlay))))
3102 ;; stacked expansion: this case is mainly for recent
3103 ;; snippet exits that place us back int the field of
3107 (yas/move-to-field snippet active-field)
3108 (yas/update-mirrors snippet)))
3111 (unless snippets-left
3112 (remove-hook 'post-command-hook 'yas/post-command-handler 'local)
3113 (remove-hook 'pre-command-hook 'yas/pre-command-handler 'local))))
3115 ;; Apropos markers-to-points:
3117 ;; This was found useful for performance reasons, so that an
3118 ;; excessive number of live markers aren't kept around in the
3119 ;; `buffer-undo-list'. However, in `markers-to-points', the
3120 ;; set-to-nil markers can't simply be discarded and replaced with
3121 ;; fresh ones in `points-to-markers'. The original marker that was
3122 ;; just set to nil has to be reused.
3124 ;; This shouldn't bring horrible problems with undo/redo, but it
3127 (defun yas/markers-to-points (snippet)
3128 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3129 where POINT is the original position of the marker and MARKER is
3130 the original marker object with the position set to nil."
3131 (dolist (field (yas/snippet-fields snippet))
3132 (let ((start (marker-position (yas/field-start field)))
3133 (end (marker-position (yas/field-end field))))
3134 (set-marker (yas/field-start field) nil)
3135 (set-marker (yas/field-end field) nil)
3136 (setf (yas/field-start field) (cons start (yas/field-start field)))
3137 (setf (yas/field-end field) (cons end (yas/field-end field))))
3138 (dolist (mirror (yas/field-mirrors field))
3139 (let ((start (marker-position (yas/mirror-start mirror)))
3140 (end (marker-position (yas/mirror-end mirror))))
3141 (set-marker (yas/mirror-start mirror) nil)
3142 (set-marker (yas/mirror-end mirror) nil)
3143 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3144 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3145 (let ((snippet-exit (yas/snippet-exit snippet)))
3147 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3148 (set-marker (yas/exit-marker snippet-exit) nil)
3149 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3151 (defun yas/points-to-markers (snippet)
3152 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3153 is done by setting MARKER to POINT with `set-marker'."
3154 (dolist (field (yas/snippet-fields snippet))
3155 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3156 (car (yas/field-start field))))
3157 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3158 (car (yas/field-end field))))
3159 (dolist (mirror (yas/field-mirrors field))
3160 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3161 (car (yas/mirror-start mirror))))
3162 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3163 (car (yas/mirror-end mirror))))))
3164 (let ((snippet-exit (yas/snippet-exit snippet)))
3166 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3167 (car (yas/exit-marker snippet-exit)))))))
3169 (defun yas/field-contains-point-p (field &optional point)
3170 (let ((point (or point
3172 (and (>= point (yas/field-start field))
3173 (<= point (yas/field-end field)))))
3175 (defun yas/field-text-for-display (field)
3176 "Return the propertized display text for field FIELD. "
3177 (buffer-substring (yas/field-start field) (yas/field-end field)))
3179 (defun yas/undo-in-progress ()
3180 "True if some kind of undo is in progress"
3181 (or undo-in-progress
3182 (eq this-command 'undo)
3183 (eq this-command 'redo)))
3185 (defun yas/make-control-overlay (snippet start end)
3186 "Creates the control overlay that surrounds the snippet and
3188 (let ((overlay (make-overlay start
3193 (overlay-put overlay 'keymap yas/keymap)
3194 (overlay-put overlay 'yas/snippet snippet)
3197 (defun yas/skip-and-clear-or-delete-char (&optional field)
3198 "Clears unmodified field if at field start, skips to next tab.
3200 Otherwise deletes a character normally by calling `delete-char'."
3202 (let ((field (or field
3203 (and yas/active-field-overlay
3204 (overlay-buffer yas/active-field-overlay)
3205 (overlay-get yas/active-field-overlay 'yas/field)))))
3207 (not (yas/field-modified-p field))
3208 (eq (point) (marker-position (yas/field-start field))))
3209 (yas/skip-and-clear field)
3212 (call-interactively 'delete-char)))))
3214 (defun yas/skip-and-clear (field)
3215 "Deletes the region of FIELD and sets it modified state to t"
3216 ;; Just before skipping-and-clearing the field, mark its children
3217 ;; fields as modified, too. If the childen have mirrors-in-fields
3218 ;; this prevents them from updating erroneously (we're skipping and
3221 (yas/mark-this-and-children-modified field)
3222 (delete-region (yas/field-start field) (yas/field-end field)))
3224 (defun yas/mark-this-and-children-modified (field)
3225 (setf (yas/field-modified-p field) t)
3226 (let ((fom (yas/field-next field)))
3228 (yas/fom-parent-field fom))
3229 (when (and (eq (yas/fom-parent-field fom) field)
3231 (yas/mark-this-and-children-modified fom))
3232 (setq fom (yas/fom-next fom)))))
3234 (defun yas/make-move-active-field-overlay (snippet field)
3235 "Place the active field overlay in SNIPPET's FIELD.
3237 Move the overlay, or create it if it does not exit."
3238 (if (and yas/active-field-overlay
3239 (overlay-buffer yas/active-field-overlay))
3240 (move-overlay yas/active-field-overlay
3241 (yas/field-start field)
3242 (yas/field-end field))
3243 (setq yas/active-field-overlay
3244 (make-overlay (yas/field-start field)
3245 (yas/field-end field)
3247 (overlay-put yas/active-field-overlay 'priority 100)
3248 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3249 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3250 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3251 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3252 '(yas/on-field-overlay-modification))
3253 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3254 '(yas/on-field-overlay-modification))))
3256 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3257 "Clears the field and updates mirrors, conditionally.
3259 Only clears the field if it hasn't been modified and it point it
3260 at field start. This hook doesn't do anything if an undo is in
3262 (unless (yas/undo-in-progress)
3263 (let* ((field (overlay-get yas/active-field-overlay 'yas/field))
3264 (number (and field (yas/field-number field)))
3265 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3267 (yas/advance-end-maybe field (overlay-end overlay))
3268 ;; primary field transform: normal calls to expression or
3269 ;; force an exit on next `post-command-hook' if the
3271 (if (and number (zerop number))
3272 (setf (yas/snippet-force-exit snippet) t)
3273 (let ((saved-point (point)))
3274 (yas/field-update-display field (car (yas/snippets-at-point)))
3275 (goto-char saved-point)))
3276 (yas/update-mirrors (car (yas/snippets-at-point))))
3278 (when (and (not after?)
3279 (not (yas/field-modified-p field))
3280 (eq (point) (if (markerp (yas/field-start field))
3281 (marker-position (yas/field-start field))
3282 (yas/field-start field))))
3283 (yas/skip-and-clear field))
3284 (setf (yas/field-modified-p field) t))))))
3286 ;;; Apropos protection overlays:
3288 ;; These exist for nasty users who will try to delete parts of the
3289 ;; snippet outside the active field. Actual protection happens in
3290 ;; `yas/on-protection-overlay-modification'.
3292 ;; Currently this signals an error which inhibits the command. For
3293 ;; commands that move point (like `kill-line'), point is restored in
3294 ;; the `yas/post-command-handler' using a global
3295 ;; `yas/protection-violation' variable.
3297 ;; Alternatively, I've experimented with an implementation that
3298 ;; commits the snippet before actually calling `this-command'
3299 ;; interactively, and then signals an eror, which is ignored. but
3300 ;; blocks all other million modification hooks. This presented some
3301 ;; problems with stacked expansion.
3304 (defun yas/make-move-field-protection-overlays (snippet field)
3305 "Place protection overlays surrounding SNIPPET's FIELD.
3307 Move the overlays, or create them if they do not exit."
3308 (let ((start (yas/field-start field))
3309 (end (yas/field-end field)))
3310 ;; First check if the (1+ end) is contained in the buffer,
3311 ;; otherwise we'll have to do a bit of cheating and silently
3312 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3313 ;; when using stacked expansion
3315 (when (< (buffer-size) end)
3317 (let ((inhibit-modification-hooks t))
3318 (goto-char (point-max))
3320 ;; go on to normal overlay creation/moving
3322 (cond ((and yas/field-protection-overlays
3323 (every #'overlay-buffer yas/field-protection-overlays))
3324 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3325 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3327 (setq yas/field-protection-overlays
3328 (list (make-overlay (1- start) start nil t nil)
3329 (make-overlay end (1+ end) nil t nil)))
3330 (dolist (ov yas/field-protection-overlays)
3331 (overlay-put ov 'face 'yas/field-debug-face)
3332 (overlay-put ov 'yas/snippet snippet)
3333 ;; (overlay-put ov 'evaporate t)
3334 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3336 (defvar yas/protection-violation nil
3337 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3339 Functions in the `post-command-hook', for example
3340 `yas/post-command-handler' can check it and reset its value to
3341 nil. The variables value is the point where the violation
3344 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3345 "Signals a snippet violation, then issues error.
3347 The error should be ignored in `debug-ignored-errors'"
3348 (cond ((not (or after?
3349 (yas/undo-in-progress)))
3350 (setq yas/protection-violation (point))
3351 (error "Exit the snippet first!"))))
3353 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3356 ;;; Apropos stacked expansion:
3358 ;; the parent snippet does not run its fields modification hooks
3359 ;; (`yas/on-field-overlay-modification' and
3360 ;; `yas/on-protection-overlay-modification') while the child snippet
3361 ;; is active. This means, among other things, that the mirrors of the
3362 ;; parent snippet are not updated, this only happening when one exits
3363 ;; the child snippet.
3365 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3366 ;; bits of code in `yas/expand-snippet' and
3367 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3370 ;; This was thought to be safer in in an undo/redo perpective, but
3371 ;; maybe the correct implementation is to make the globals
3372 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3373 ;; snippet-local and be active even while the child snippet is
3374 ;; running. This would mean a lot of overlay modification hooks
3375 ;; running, but if managed correctly (including overlay priorities)
3376 ;; they should account for all situations...
3379 (defun yas/expand-snippet (content &optional start end expand-env)
3380 "Expand snippet CONTENT at current point.
3382 Text between START and END will be deleted before inserting
3383 template. EXPAND-ENV is are let-style variable to value bindings
3384 considered when expanding the snippet."
3385 (run-hooks 'yas/before-expand-snippet-hook)
3387 ;; If a region is active, set `yas/selected-text'
3388 (setq yas/selected-text
3390 (prog1 (buffer-substring-no-properties (region-beginning)
3392 (unless start (setq start (region-beginning))
3393 (unless end (setq end (region-end)))))))
3399 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3400 (start (or start (point)))
3401 (end (or end (point)))
3402 (column (current-column))
3404 ;; Delete the region to delete, this *does* get undo-recorded.
3406 (when (and to-delete
3408 (delete-region start end)
3409 (setq yas/deleted-text to-delete))
3411 (cond ((listp content)
3412 ;; x) This is a snippet-command
3414 (yas/eval-lisp-no-saves content))
3416 ;; x) This is a snippet-snippet :-)
3418 ;; Narrow the region down to the content, shoosh the
3419 ;; `buffer-undo-list', and create the snippet, the new
3420 ;; snippet updates its mirrors once, so we are left with
3421 ;; some plain text. The undo action for deleting this
3422 ;; plain text will get recorded at the end.
3424 ;; stacked expansion: also shoosh the overlay modification hooks
3426 (narrow-to-region start start)
3427 (let ((inhibit-modification-hooks t)
3428 (buffer-undo-list t))
3429 ;; snippet creation might evaluate users elisp, which
3430 ;; might generate errors, so we have to be ready to catch
3431 ;; them mostly to make the undo information
3433 (setq yas/start-column (save-restriction (widen) (current-column)))
3437 (eval `(let ,expand-env
3439 (yas/snippet-create (point-min) (point-max))))
3441 (yas/snippet-create (point-min) (point-max))))))
3443 ;; stacked-expansion: This checks for stacked expansion, save the
3444 ;; `yas/previous-active-field' and advance its boudary.
3446 (let ((existing-field (and yas/active-field-overlay
3447 (overlay-buffer yas/active-field-overlay)
3448 (overlay-get yas/active-field-overlay 'yas/field))))
3449 (when existing-field
3450 (setf (yas/snippet-previous-active-field snippet) existing-field)
3451 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3453 ;; Exit the snippet immediately if no fields
3455 (unless (yas/snippet-fields snippet)
3456 (yas/exit-snippet snippet))
3458 ;; Push two undo actions: the deletion of the inserted contents of
3459 ;; the new snippet (without the "key") followed by an apply of
3460 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3462 ;; A small exception, if `yas/also-auto-indent-first-line'
3463 ;; is t and `yas/indent' decides to indent the line to a
3464 ;; point before the actual expansion point, undo would be
3465 ;; messed up. We call the early point "newstart"". case,
3466 ;; and attempt to fix undo.
3468 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3469 (end (overlay-end (yas/snippet-control-overlay snippet))))
3470 (when (< newstart start)
3471 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3472 (push (cons newstart end) buffer-undo-list)
3473 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3475 ;; Now, schedule a move to the first field
3477 (let ((first-field (car (yas/snippet-fields snippet))))
3479 (sit-for 0) ;; fix issue 125
3480 (yas/move-to-field snippet first-field))))
3481 (message "[yas] snippet expanded."))))
3483 (defun yas/take-care-of-redo (beg end snippet)
3484 "Commits SNIPPET, which in turn pushes an undo action for
3487 Meant to exit in the `buffer-undo-list'."
3488 ;; slightly optimize: this action is only needed for snippets with
3489 ;; at least one field
3490 (when (yas/snippet-fields snippet)
3491 (yas/commit-snippet snippet 'no-hooks)))
3493 (defun yas/snippet-revive (beg end snippet)
3494 "Revives the SNIPPET and creates a control overlay from BEG to
3497 BEG and END are, we hope, the original snippets boudaries. All
3498 the markers/points exiting existing inside SNIPPET should point
3499 to their correct locations *at the time the snippet is revived*.
3501 After revival, push the `yas/take-care-of-redo' in the
3503 ;; Reconvert all the points to markers
3505 (yas/points-to-markers snippet)
3506 ;; When at least one editable field existed in the zombie snippet,
3507 ;; try to revive the whole thing...
3509 (let ((target-field (or (yas/snippet-active-field snippet)
3510 (car (yas/snippet-fields snippet)))))
3512 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3513 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3515 (yas/move-to-field snippet target-field)
3517 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
3518 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
3520 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3521 buffer-undo-list))))
3523 (defun yas/snippet-create (begin end)
3524 "Creates a snippet from an template inserted between BEGIN and END.
3526 Returns the newly created snippet."
3527 (let ((snippet (yas/make-snippet)))
3529 (yas/snippet-parse-create snippet)
3531 ;; Sort and link each field
3532 (yas/snippet-sort-fields snippet)
3534 ;; Create keymap overlay for snippet
3535 (setf (yas/snippet-control-overlay snippet)
3536 (yas/make-control-overlay snippet (point-min) (point-max)))
3539 (goto-char (point-max))
3542 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
3543 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
3548 ;;; Apropos adjacencies and "fom's":
3550 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3551 ;; recently expanded snippet, we might actually have many fields,
3552 ;; mirrors (and the snippet exit) in the very same position in the
3553 ;; buffer. Therefore we need to single-link the
3554 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3555 ;; their original positions in the buffer.
3557 ;; Then we have operation `yas/advance-end-maybe' and
3558 ;; `yas/advance-start-maybe', which conditionally push the starts and
3559 ;; ends of these foms down the chain.
3561 ;; This allows for like the printf with the magic ",":
3563 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3564 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3566 (defun yas/fom-start (fom)
3567 (cond ((yas/field-p fom)
3568 (yas/field-start fom))
3570 (yas/mirror-start fom))
3572 (yas/exit-marker fom))))
3574 (defun yas/fom-end (fom)
3575 (cond ((yas/field-p fom)
3576 (yas/field-end fom))
3578 (yas/mirror-end fom))
3580 (yas/exit-marker fom))))
3582 (defun yas/fom-next (fom)
3583 (cond ((yas/field-p fom)
3584 (yas/field-next fom))
3586 (yas/mirror-next fom))
3588 (yas/exit-next fom))))
3590 (defun yas/fom-parent-field (fom)
3591 (cond ((yas/field-p fom)
3592 (yas/field-parent-field fom))
3594 (yas/mirror-parent-field fom))
3598 (defun yas/calculate-adjacencies (snippet)
3599 "Calculate adjacencies for fields or mirrors of SNIPPET.
3601 This is according to their relative positions in the buffer, and
3602 has to be called before the $-constructs are deleted."
3603 (flet ((yas/fom-set-next-fom (fom nextfom)
3604 (cond ((yas/field-p fom)
3605 (setf (yas/field-next fom) nextfom))
3607 (setf (yas/mirror-next fom) nextfom))
3609 (setf (yas/exit-next fom) nextfom))))
3610 (yas/compare-fom-begs (fom1 fom2)
3611 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3613 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3614 (yas/link-foms (fom1 fom2)
3615 (yas/fom-set-next-fom fom1 fom2)))
3616 ;; make some yas/field, yas/mirror and yas/exit soup
3618 (when (yas/snippet-exit snippet)
3619 (push (yas/snippet-exit snippet) soup))
3620 (dolist (field (yas/snippet-fields snippet))
3622 (dolist (mirror (yas/field-mirrors field))
3623 (push mirror soup)))
3626 #'yas/compare-fom-begs))
3628 (reduce #'yas/link-foms soup)))))
3630 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3631 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3633 Use the tighest containing field if more than one field contains
3634 the mirror. Intended to be called *before* the dollar-regions are
3636 (let ((min (point-min))
3638 (dolist (field (yas/snippet-fields snippet))
3639 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3640 (<= (yas/mirror-end mirror) (yas/field-end field))
3641 (< min (yas/field-start field))
3642 (< (yas/field-end field) max))
3643 (setq min (yas/field-start field)
3644 max (yas/field-end field))
3645 (setf (yas/mirror-parent-field mirror) field)))))
3647 (defun yas/advance-end-maybe (fom newend)
3648 "Maybe advance FOM's end to NEWEND if it needs it.
3652 * call `yas/advance-start-maybe' on FOM's next fom.
3654 * in case FOM is field call `yas/advance-end-maybe' on its parent
3657 Also, if FOM is an exit-marker, always call
3658 `yas/advance-start-maybe' on its next fom. This is beacuse
3659 exit-marker have identical start and end markers.
3662 (cond ((and fom (< (yas/fom-end fom) newend))
3663 (set-marker (yas/fom-end fom) newend)
3664 (yas/advance-start-maybe (yas/fom-next fom) newend)
3665 (let ((parent (yas/fom-parent-field fom)))
3667 (yas/advance-end-maybe parent newend))))
3669 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3671 (defun yas/advance-start-maybe (fom newstart)
3672 "Maybe advance FOM's start to NEWSTART if it needs it.
3674 If it does, also call `yas/advance-end-maybe' on FOM."
3675 (when (and fom (< (yas/fom-start fom) newstart))
3676 (set-marker (yas/fom-start fom) newstart)
3677 (yas/advance-end-maybe fom newstart)))
3679 (defun yas/advance-end-of-parents-maybe (field newend)
3680 "Like `yas/advance-end-maybe' but for parents."
3682 (< (yas/field-end field) newend))
3683 (set-marker (yas/field-end field) newend)
3684 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3686 (defvar yas/dollar-regions nil
3687 "When expanding the snippet the \"parse-create\" functions add
3688 cons cells to this var")
3690 (defun yas/snippet-parse-create (snippet)
3691 "Parse a recently inserted snippet template, creating all
3692 necessary fields, mirrors and exit points.
3694 Meant to be called in a narrowed buffer, does various passes"
3695 (let ((parse-start (point)))
3696 ;; Reset the yas/dollar-regions
3698 (setq yas/dollar-regions nil)
3699 ;; protect escaped quote, backquotes and backslashes
3701 (yas/protect-escapes nil '(?\\ ?` ?'))
3702 ;; replace all backquoted expressions
3704 (goto-char parse-start)
3705 (yas/replace-backquotes)
3706 ;; protect escapes again since previous steps might have generated
3707 ;; more characters needing escaping
3709 (goto-char parse-start)
3710 (yas/protect-escapes)
3711 ;; parse fields with {}
3713 (goto-char parse-start)
3714 (yas/field-parse-create snippet)
3715 ;; parse simple mirrors and fields
3717 (goto-char parse-start)
3718 (yas/simple-mirror-parse-create snippet)
3719 ;; parse mirror transforms
3721 (goto-char parse-start)
3722 (yas/transform-mirror-parse-create snippet)
3723 ;; calculate adjacencies of fields and mirrors
3725 (yas/calculate-adjacencies snippet)
3726 ;; Delete $-constructs
3728 (yas/delete-regions yas/dollar-regions)
3731 (goto-char parse-start)
3732 (yas/restore-escapes)
3733 ;; update mirrors for the first time
3735 (yas/update-mirrors snippet)
3736 ;; indent the best we can
3738 (goto-char parse-start)
3739 (yas/indent snippet)))
3741 (defun yas/indent-according-to-mode (snippet-markers)
3742 "Indent current line according to mode, preserving
3744 ;;; Apropos indenting problems....
3746 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3747 ;; is available. Some implementations of these functions delete text
3748 ;; before they insert. If there happens to be a marker just after
3749 ;; the text being deleted, the insertion actually happens after the
3750 ;; marker, which misplaces it.
3752 ;; This would also happen if we had used overlays with the
3753 ;; `front-advance' property set to nil.
3755 ;; This is why I have these `trouble-markers', they are the ones at
3756 ;; they are the ones at the first non-whitespace char at the line
3757 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3758 ;; we should be at the correct to restore them to. All other
3759 ;; non-trouble-markers have been *pushed* and don't need special
3762 (goto-char (yas/real-line-beginning))
3763 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3769 (indent-according-to-mode)
3770 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3772 (mapc #'(lambda (marker)
3773 (set-marker marker (point)))
3776 (defun yas/indent (snippet)
3777 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3778 ;; Look for those $>
3780 (while (re-search-forward "$>" nil t)
3781 (delete-region (match-beginning 0) (match-end 0))
3782 (when (not (eq yas/indent-line 'auto))
3783 (yas/indent-according-to-mode snippet-markers))))
3784 ;; Now do stuff for 'fixed and 'auto
3786 (cond ((eq yas/indent-line 'fixed)
3787 (while (and (zerop (forward-line))
3788 (zerop (current-column)))
3789 (indent-to-column column)))
3790 ((eq yas/indent-line 'auto)
3791 (let ((end (set-marker (make-marker) (point-max)))
3792 (indent-first-line-p yas/also-auto-indent-first-line))
3793 (while (and (zerop (if indent-first-line-p
3796 (setq indent-first-line-p nil))
3800 (yas/indent-according-to-mode snippet-markers))))
3804 (defun yas/collect-snippet-markers (snippet)
3805 "Make a list of all the markers used by SNIPPET."
3807 (dolist (field (yas/snippet-fields snippet))
3808 (push (yas/field-start field) markers)
3809 (push (yas/field-end field) markers)
3810 (dolist (mirror (yas/field-mirrors field))
3811 (push (yas/mirror-start mirror) markers)
3812 (push (yas/mirror-end mirror) markers)))
3813 (let ((snippet-exit (yas/snippet-exit snippet)))
3814 (when (and snippet-exit
3815 (marker-buffer (yas/exit-marker snippet-exit)))
3816 (push (yas/exit-marker snippet-exit) markers)))
3819 (defun yas/real-line-beginning ()
3820 (let ((c (char-after (line-beginning-position)))
3821 (n (line-beginning-position)))
3822 (while (or (eql c ?\ )
3825 (setq c (char-after n)))
3828 (defun yas/escape-string (escaped)
3829 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3831 (defun yas/protect-escapes (&optional text escaped)
3832 "Protect all escaped characters with their numeric ASCII value.
3834 With optional string TEXT do it in string instead of buffer."
3835 (let ((changed-text text)
3836 (text-provided-p text))
3837 (mapc #'(lambda (escaped)
3839 (yas/replace-all (concat "\\" (char-to-string escaped))
3840 (yas/escape-string escaped)
3841 (when text-provided-p changed-text))))
3842 (or escaped yas/escaped-characters))
3845 (defun yas/restore-escapes (&optional text escaped)
3846 "Restore all escaped characters from their numeric ASCII value.
3848 With optional string TEXT do it in string instead of the buffer."
3849 (let ((changed-text text)
3850 (text-provided-p text))
3851 (mapc #'(lambda (escaped)
3853 (yas/replace-all (yas/escape-string escaped)
3854 (char-to-string escaped)
3855 (when text-provided-p changed-text))))
3856 (or escaped yas/escaped-characters))
3859 (defun yas/replace-backquotes ()
3860 "Replace all the \"`(lisp-expression)`\"-style expression
3861 with their evaluated value"
3862 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3863 (let ((transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes (match-string 1))))))
3864 (goto-char (match-end 0))
3865 (when transformed (insert transformed))
3866 (delete-region (match-beginning 0) (match-end 0)))))
3868 (defun yas/scan-sexps (from count)
3870 (with-syntax-table (standard-syntax-table)
3871 (scan-sexps from count))
3875 (defun yas/make-marker (pos)
3876 "Create a marker at POS with `nil' `marker-insertion-type'"
3877 (let ((marker (set-marker (make-marker) pos)))
3878 (set-marker-insertion-type marker nil)
3881 (defun yas/field-parse-create (snippet &optional parent-field)
3882 "Parse most field expressions, except for the simple one \"$n\".
3884 The following count as a field:
3886 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3888 * \"${n: text$(expression)}, the same with a lisp expression;
3889 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3891 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3893 When multiple expressions are found, only the last one counts."
3896 (while (re-search-forward yas/field-regexp nil t)
3897 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3898 (number (and (match-string-no-properties 1)
3899 (string-to-number (match-string-no-properties 1))))
3900 (brand-new-field (and real-match-end-0
3901 ;; break if on "$(" immediately
3902 ;; after the ":", this will be
3903 ;; caught as a mirror with
3905 (not (save-match-data
3906 (eq (string-match "$[ \t\n]*("
3907 (match-string-no-properties 2)) 0)))
3908 ;; allow ${0: some exit text}
3909 ;; (not (and number (zerop number)))
3910 (yas/make-field number
3911 (yas/make-marker (match-beginning 2))
3912 (yas/make-marker (1- real-match-end-0))
3914 (when brand-new-field
3915 (goto-char real-match-end-0)
3916 (push (cons (1- real-match-end-0) real-match-end-0)
3918 (push (cons (match-beginning 0) (match-beginning 2))
3920 (push brand-new-field (yas/snippet-fields snippet))
3923 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3924 (goto-char (point-min))
3925 (yas/field-parse-create snippet brand-new-field)))))))
3926 ;; if we entered from a parent field, now search for the
3927 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3928 ;; primary field transformations
3932 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3933 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3934 ;; commit the primary field transformation if:
3936 ;; 1. we don't find it in yas/dollar-regions (a subnested
3937 ;; field) might have already caught it.
3939 ;; 2. we really make sure we have either two '$' or some
3940 ;; text and a '$' after the colon ':'. This is a FIXME: work
3941 ;; my regular expressions and end these ugly hacks.
3943 (when (and real-match-end-1
3944 (not (member (cons (match-beginning 0)
3946 yas/dollar-regions))
3948 (char-before (1- (match-beginning 1))))))
3949 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3951 (setf (yas/field-transform parent-field)
3952 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3953 (push (cons (match-beginning 0) real-match-end-1)
3954 yas/dollar-regions)))))))
3956 (defun yas/transform-mirror-parse-create (snippet)
3957 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3958 (while (re-search-forward yas/transform-mirror-regexp nil t)
3959 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3960 (number (string-to-number (match-string-no-properties 1)))
3962 (not (zerop number))
3963 (yas/snippet-find-field snippet number)))
3965 (and real-match-end-0
3967 (yas/make-mirror (yas/make-marker (match-beginning 0))
3968 (yas/make-marker (match-beginning 0))
3970 (yas/restore-escapes
3971 (buffer-substring-no-properties (match-beginning 2)
3972 (1- real-match-end-0))))))))
3973 (when brand-new-mirror
3974 (push brand-new-mirror
3975 (yas/field-mirrors field))
3976 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3977 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3979 (defun yas/simple-mirror-parse-create (snippet)
3980 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3981 (while (re-search-forward yas/simple-mirror-regexp nil t)
3982 (let ((number (string-to-number (match-string-no-properties 1))))
3983 (cond ((zerop number)
3985 (setf (yas/snippet-exit snippet)
3986 (yas/make-exit (yas/make-marker (match-end 0))))
3988 (goto-char (match-beginning 0))
3989 (when yas/wrap-around-region
3990 (cond (yas/selected-text
3991 (insert yas/selected-text))
3992 ((and (eq yas/wrap-around-region 'cua)
3995 (insert (prog1 (get-register ?0)
3996 (set-register ?0 nil))))))
3997 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3998 yas/dollar-regions)))
4000 (let ((field (yas/snippet-find-field snippet number)))
4002 (let ((brand-new-mirror (yas/make-mirror
4003 (yas/make-marker (match-beginning 0))
4004 (yas/make-marker (match-beginning 0))
4006 (push brand-new-mirror
4007 (yas/field-mirrors field))
4008 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
4009 (push (yas/make-field number
4010 (yas/make-marker (match-beginning 0))
4011 (yas/make-marker (match-beginning 0))
4013 (yas/snippet-fields snippet))))
4014 (push (cons (match-beginning 0) (match-end 0))
4015 yas/dollar-regions))))))
4017 (defun yas/delete-regions (regions)
4018 "Sort disjuct REGIONS by start point, then delete from the back."
4019 (mapc #'(lambda (reg)
4020 (delete-region (car reg) (cdr reg)))
4023 (>= (car r1) (car r2))))))
4025 (defun yas/update-mirrors (snippet)
4026 "Updates all the mirrors of SNIPPET."
4028 (let* ((fields (copy-list (yas/snippet-fields snippet)))
4029 (field (car fields)))
4031 (dolist (mirror (yas/field-mirrors field))
4032 ;; stacked expansion: I added an `inhibit-modification-hooks'
4033 ;; here, for safety, may need to remove if we the mechanism is
4036 (let ((inhibit-modification-hooks t)
4037 (mirror-parent-field (yas/mirror-parent-field mirror)))
4038 ;; updatte this mirror
4040 (yas/mirror-update-display mirror field)
4041 ;; for mirrors-in-fields: schedule a possible
4042 ;; parent field for reupdting later on
4044 (when mirror-parent-field
4045 (add-to-list 'fields mirror-parent-field 'append #'eq))
4046 ;; `yas/place-overlays' is needed if the active field and
4047 ;; protected overlays have been changed because of insertions
4048 ;; in `yas/mirror-update-display'
4050 (when (eq field (yas/snippet-active-field snippet))
4051 (yas/place-overlays snippet field))))
4052 (setq fields (cdr fields))
4053 (setq field (car fields))))))
4055 (defun yas/mirror-update-display (mirror field)
4056 "Update MIRROR according to FIELD (and mirror transform)."
4058 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
4059 (reflection (and (not (and mirror-parent-field
4060 (yas/field-modified-p mirror-parent-field)))
4061 (or (yas/apply-transform mirror field)
4062 (yas/field-text-for-display field)))))
4063 (when (and reflection
4064 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
4065 (yas/mirror-end mirror)))))
4066 (goto-char (yas/mirror-start mirror))
4068 (if (> (yas/mirror-end mirror) (point))
4069 (delete-region (point) (yas/mirror-end mirror))
4070 (set-marker (yas/mirror-end mirror) (point))
4071 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
4072 ;; super-special advance
4073 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
4075 (defun yas/field-update-display (field snippet)
4076 "Much like `yas/mirror-update-display', but for fields"
4077 (when (yas/field-transform field)
4078 (let ((inhibit-modification-hooks t)
4079 (transformed (yas/apply-transform field field))
4081 (when (and transformed
4082 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4083 (yas/field-end field)))))
4084 (setf (yas/field-modified-p field) t)
4085 (goto-char (yas/field-start field))
4086 (insert transformed)
4087 (if (> (yas/field-end field) (point))
4088 (delete-region (point) (yas/field-end field))
4089 (set-marker (yas/field-end field) (point))
4090 (yas/advance-start-maybe (yas/field-next field) (point)))
4094 ;;; Pre- and post-command hooks:
4096 (defvar yas/post-command-runonce-actions nil
4097 "List of actions to run once `post-command-hook'.
4099 Each element of this list looks like (FN . ARGS) where FN is
4100 called with ARGS as its arguments after the currently executing
4103 After all actions have been run, this list is emptied, and after
4104 that the rest of `yas/post-command-handler' runs.")
4106 (defun yas/pre-command-handler () )
4108 (defun yas/post-command-handler ()
4109 "Handles various yasnippet conditions after each command."
4110 (when yas/post-command-runonce-actions
4112 (mapc #'(lambda (fn-and-args)
4113 (apply (car fn-and-args)
4115 yas/post-command-runonce-actions)
4116 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4117 (setq yas/post-command-runonce-actions nil))
4118 (cond (yas/protection-violation
4119 (goto-char yas/protection-violation)
4120 (setq yas/protection-violation nil))
4121 ((eq 'undo this-command)
4123 ;; After undo revival the correct field is sometimes not
4124 ;; restored correctly, this condition handles that
4126 (let* ((snippet (car (yas/snippets-at-point)))
4127 (target-field (and snippet
4128 (find-if-not #'(lambda (field)
4129 (yas/field-probably-deleted-p snippet field))
4131 (cons (yas/snippet-active-field snippet)
4132 (yas/snippet-fields snippet)))))))
4134 (yas/move-to-field snippet target-field))))
4135 ((not (yas/undo-in-progress))
4136 ;; When not in an undo, check if we must commit the snippet
4137 ;; (user exited it).
4138 (yas/check-commit-snippet))))
4142 (put 'yas/expand 'function-documentation '(yas/expand-from-trigger-key-doc))
4143 (defun yas/expand-from-trigger-key-doc ()
4144 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4145 (let ((fallback-description
4146 (cond ((eq yas/fallback-behavior 'call-other-command)
4147 (let* ((yas/minor-mode nil)
4148 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4150 (format " call command `%s'." (pp-to-string fallback)))
4152 ((eq yas/fallback-behavior 'return-nil)
4155 ", defer to `yas/fallback-behaviour' :-)"))))
4156 (concat "Expand a snippet before point. If no snippet
4157 expansion is possible,"
4158 fallback-description
4159 "\n\nOptional argument FIELD is for non-interactive use and is an
4160 object satisfying `yas/field-p' to restrict the expansion to.")))
4162 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4163 (defun yas/expand-from-keymap-doc ()
4164 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4165 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4166 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4167 (when (eq this-command 'describe-key)
4168 (let* ((vec (this-single-command-keys))
4169 (templates (mapcan #'(lambda (table)
4170 (yas/fetch table vec))
4171 (yas/get-snippet-tables)))
4172 (yas/direct-keymaps nil)
4173 (fallback (key-binding vec)))
4174 (concat "In this case, "
4176 (concat "these snippets are bound to this key:\n"
4177 (yas/template-pretty-list templates)
4178 "\n\nIf none of these expands, "))
4180 (format "fallback `%s' will be called." (pp-to-string fallback)))
4181 "no fallback keybinding is called."))))))
4183 (defun yas/template-pretty-list (templates)
4185 (yas/buffer-local-condition 'always))
4186 (dolist (plate templates)
4187 (setq acc (concat acc "\n*) "
4188 (propertize (concat "\\\\snippet `" (car plate) "'")
4189 'yasnippet (cdr plate)))))
4192 (define-button-type 'help-snippet-def
4193 :supertype 'help-xref
4194 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4195 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4197 (defun yas/snippet-description-finish-runonce ()
4198 "Final adjustments for the help buffer when snippets are concerned."
4199 (yas/create-snippet-xrefs)
4200 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4202 (defun yas/create-snippet-xrefs ()
4204 (goto-char (point-min))
4205 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+\\(`[^']+'\\)" nil t)
4206 (let ((template (get-text-property (match-beginning 1)
4209 (help-xref-button 1 'help-snippet-def template)
4210 (kill-region (match-beginning 0) (match-beginning 1)))))))
4212 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4213 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4215 Remaining args as in `yas/expand-snippet'."
4216 (let* ((table (gethash mode-symbol yas/tables))
4217 (yas/current-template (and table
4218 (gethash uuid (yas/table-uuidhash table)))))
4219 (when yas/current-template
4220 (yas/expand-snippet (yas/template-content yas/current-template)))))
4224 ;; `locate-dominating-file' is added for compatibility in emacs < 23
4225 (unless (or (eq emacs-major-version 23)
4226 (fboundp 'locate-dominating-file))
4227 (defvar locate-dominating-stop-dir-regexp
4228 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4229 "Regexp of directory names which stop the search in `locate-dominating-file'.
4230 Any directory whose name matches this regexp will be treated like
4231 a kind of root directory by `locate-dominating-file' which will stop its search
4232 when it bumps into it.
4233 The default regexp prevents fruitless and time-consuming attempts to find
4234 special files in directories in which filenames are interpreted as hostnames,
4235 or mount points potentially requiring authentication as a different user.")
4237 (defun locate-dominating-file (file name)
4238 "Look up the directory hierarchy from FILE for a file named NAME.
4239 Stop at the first parent directory containing a file NAME,
4240 and return the directory. Return nil if not found."
4241 ;; We used to use the above locate-dominating-files code, but the
4242 ;; directory-files call is very costly, so we're much better off doing
4243 ;; multiple calls using the code in here.
4245 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4246 ;; `name' in /home or in /.
4247 (setq file (abbreviate-file-name file))
4250 ;; `user' is not initialized outside the loop because
4251 ;; `file' may not exist, so we may have to walk up part of the
4252 ;; hierarchy before we find the "initial UUID".
4255 (while (not (or root
4257 ;; FIXME: Disabled this heuristic because it is sometimes
4259 ;; As a heuristic, we stop looking up the hierarchy of
4260 ;; directories as soon as we find a directory belonging
4261 ;; to another user. This should save us from looking in
4262 ;; things like /net and /afs. This assumes that all the
4263 ;; files inside a project belong to the same user.
4264 ;; (let ((prev-user user))
4265 ;; (setq user (nth 2 (file-attributes file)))
4266 ;; (and prev-user (not (equal user prev-user))))
4267 (string-match locate-dominating-stop-dir-regexp file)))
4268 (setq try (file-exists-p (expand-file-name name file)))
4269 (cond (try (setq root file))
4270 ((equal file (setq prev-file file
4271 file (file-name-directory
4272 (directory-file-name file))))
4276 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4277 ;; (when it execute forward-char) and interrupt the after change
4278 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4279 ;; invoked. Here's a way to reproduce it:
4281 ;; # open a *new* Emacs.
4282 ;; # load yasnippet.
4283 ;; # open a *new* .cpp file.
4284 ;; # input "inc" and press TAB to expand the snippet.
4285 ;; # select the `#include <...>` snippet.
4286 ;; # type inside `<>`
4288 (defadvice c-neutralize-syntax-in-CPP
4289 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4290 "Adviced `c-neutralize-syntax-in-CPP' to properly
4291 handle the end-of-buffer error fired in it by calling
4292 `forward-char' at the end of buffer."
4295 (error (message (error-message-string err)))))
4297 ;; disable c-electric-* serial command in YAS fields
4298 (add-hook 'c-mode-common-hook
4300 (dolist (k '(":" ">" ";" "<" "{" "}"))
4301 (define-key (symbol-value (make-local-variable 'yas/keymap))
4302 k 'self-insert-command))))
4304 (provide 'yasnippet)
4306 ;;; yasnippet.el ends here