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://github.com/capitaomorte/yasnippet
10 ;; Keywords: convenience, emulation
11 ;; URL: http://github.com/capitaomorte/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 ;; (add-to-list 'load-path
34 ;; "~/.emacs.d/plugins/yasnippet")
35 ;; (require 'yasnippet)
36 ;; (yas/global-mode 1)
39 ;; Interesting variables are:
43 ;; The directory where user-created snippets are to be
44 ;; stored. Can also be a list of directories. In that case,
45 ;; when used for bulk (re)loading of snippets (at startup or
46 ;; via `yas/reload-all'), directories appearing earlier in
47 ;; the list shadow other dir's snippets. Also, the first
48 ;; directory is taken as the default for storing the user's
51 ;; The deprecated `yas/root-directory' aliases this variable
52 ;; for backward-compatibility.
56 ;; A local variable that you can set in a hook to override
57 ;; snippet-lookup based on major mode. It is a a symbol (or
58 ;; list of symbols) that correspond to subdirectories of
59 ;; `yas/snippet-dirs' and is used for deciding which
60 ;; snippets to consider for the active buffer.
62 ;; Deprecated `yas/mode-symbol' aliases this variable for
63 ;; backward-compatibility.
65 ;; Major commands are:
69 ;; Try to expand snippets before point. In `yas/minor-mode',
70 ;; this is bound to `yas/trigger-key' which you can customize.
72 ;; M-x yas/load-directory
74 ;; Prompts you for a directory hierarchy of snippets to load.
76 ;; M-x yas/insert-snippet
78 ;; Prompts you for possible snippet expansion if that is
79 ;; possible according to buffer-local and snippet-local
80 ;; expansion conditions. With prefix argument, ignore these
83 ;; M-x yas/find-snippets
85 ;; Lets you find the snippet files in the correct
86 ;; subdirectory of `yas/snippet-dirs', according to the
87 ;; active major mode (if it exists) like
88 ;; `find-file-other-window'.
90 ;; M-x yas/visit-snippet-file
92 ;; Prompts you for possible snippet expansions like
93 ;; `yas/insert-snippet', but instead of expanding it, takes
94 ;; you directly to the snippet definition's file, if it
97 ;; M-x yas/new-snippet
99 ;; Lets you create a new snippet file in the correct
100 ;; subdirectory of `yas/snippet-dirs', according to the
101 ;; active major mode.
103 ;; M-x yas/load-snippet-buffer
105 ;; When editing a snippet, this loads the snippet. This is
106 ;; bound to "C-c C-c" while in the `snippet-mode' editing
109 ;; M-x yas/tryout-snippet
111 ;; When editing a snippet, this opens a new empty buffer,
112 ;; sets it to the appropriate major mode and inserts the
113 ;; snippet there, so you can see what it looks like. This is
114 ;; bound to "C-c C-t" while in `snippet-mode'.
116 ;; M-x yas/describe-tables
118 ;; Lists known snippets in a separate buffer. User is
119 ;; prompted as to whether only the currently active tables
120 ;; are to be displayed, or all the tables for all major
123 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
124 ;; can optionally use it the preferred "prompting method", puting in
125 ;; your .emacs file, for example:
127 ;; (require 'dropdown-list)
128 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
130 ;; yas/completing-prompt))
132 ;; Also check out the customization group
134 ;; M-x customize-group RET yasnippet RET
136 ;; If you use the customization group to set variables
137 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
138 ;; "yasnippet.el" is present in the `load-path' *before* the
139 ;; `custom-set-variables' is executed in your .emacs file.
141 ;; For more information and detailed usage, refer to the project page:
142 ;; http://github.com/capitaomorte/yasnippet
152 ;;; User customizable variables
154 (defgroup yasnippet nil
155 "Yet Another Snippet extension"
158 (defvar yas/load-file-name load-file-name
159 "Store the filename that yasnippet.el was originally loaded from.")
160 (defcustom yas/snippet-dirs (remove nil
161 (list "~/.emacs.d/snippets"
162 (when yas/load-file-name
163 (concat (file-name-directory yas/load-file-name) "snippets"))))
164 "Directory or list of snippet dirs for each major mode.
166 The directory where user-created snippets are to be stored. Can
167 also be a list of directories. In that case, when used for
168 bulk (re)loading of snippets (at startup or via
169 `yas/reload-all'), directories appearing earlier in the list
170 shadow other dir's snippets. Also, the first directory is taken
171 as the default for storing the user's new snippets."
172 :type '(choice (string :tag "Single directory (string)")
173 (repeat :args (string) :tag "List of directories (strings)"))
176 :set #'(lambda (symbol new)
177 (let ((old (and (boundp symbol)
178 (symbol-value symbol))))
179 (set-default symbol new)
180 (unless (or (not (fboundp 'yas/reload-all))
183 (defun yas/snippet-dirs ()
184 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
187 (defcustom yas/prompt-functions '(yas/x-prompt
189 yas/completing-prompt
192 "Functions to prompt for keys, templates, etc interactively.
194 These functions are called with the following arguments:
196 - PROMPT: A string to prompt the user
198 - CHOICES: a list of strings or objects.
200 - optional DISPLAY-FN : A function that, when applied to each of
201 the objects in CHOICES will return a string.
203 The return value of any function you put here should be one of
204 the objects in CHOICES, properly formatted with DISPLAY-FN (if
207 - To signal that your particular style of prompting is
208 unavailable at the moment, you can also have the function return
211 - To signal that the user quit the prompting process, you can
214 (signal 'quit \"user quit!\")."
215 :type '(repeat function)
218 (defcustom yas/indent-line 'auto
219 "Controls indenting applied to a recent snippet expansion.
221 The following values are possible:
223 - `fixed' Indent the snippet to the current column;
225 - `auto' Indent each line of the snippet with `indent-according-to-mode'
227 Every other value means don't apply any snippet-side indendation
228 after expansion (the manual per-line \"$>\" indentation still
230 :type '(choice (const :tag "Nothing" nothing)
231 (const :tag "Fixed" fixed)
232 (const :tag "Auto" auto))
235 (defcustom yas/also-auto-indent-first-line nil
236 "Non-nil means also auto indent first line according to mode.
238 Naturally this is only valid when `yas/indent-line' is `auto'"
242 (defcustom yas/snippet-revival t
243 "Non-nil means re-activate snippet fields after undo/redo."
247 (defcustom yas/trigger-key "TAB"
248 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
250 Value is a string that is converted to the internal Emacs key
251 representation using `read-kbd-macro'."
254 :set #'(lambda (symbol key)
255 (let ((old (and (boundp symbol)
256 (symbol-value symbol))))
257 (set-default symbol key)
258 ;; On very first loading of this defcustom,
259 ;; `yas/trigger-key' is *not* loaded.
260 (if (fboundp 'yas/trigger-key-reload)
261 (yas/trigger-key-reload old)))))
263 (defcustom yas/next-field-key '("TAB" "<tab>")
264 "The key to navigate to next field when a snippet is active.
266 Value is a string that is converted to the internal Emacs key
267 representation using `read-kbd-macro'.
269 Can also be a list of strings."
270 :type '(choice (string :tag "String")
271 (repeat :args (string) :tag "List of strings"))
273 :set #'(lambda (symbol val)
274 (set-default symbol val)
275 (if (fboundp 'yas/init-yas-in-snippet-keymap)
276 (yas/init-yas-in-snippet-keymap))))
279 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
280 "The key to navigate to previous field when a snippet is active.
282 Value is a string that is converted to the internal Emacs key
283 representation using `read-kbd-macro'.
285 Can also be a list of strings."
286 :type '(choice (string :tag "String")
287 (repeat :args (string) :tag "List of strings"))
289 :set #'(lambda (symbol val)
290 (set-default symbol val)
291 (if (fboundp 'yas/init-yas-in-snippet-keymap)
292 (yas/init-yas-in-snippet-keymap))))
294 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
295 "The key to clear the currently active field.
297 Value is a string that is converted to the internal Emacs key
298 representation using `read-kbd-macro'.
300 Can also be a list of strings."
301 :type '(choice (string :tag "String")
302 (repeat :args (string) :tag "List of strings"))
304 :set #'(lambda (symbol val)
305 (set-default symbol val)
306 (if (fboundp 'yas/init-yas-in-snippet-keymap)
307 (yas/init-yas-in-snippet-keymap))))
309 (defcustom yas/triggers-in-field nil
310 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
312 Otherwise, `yas/next-field-key' just tries to move on to the next
317 (defcustom yas/fallback-behavior 'call-other-command
318 "How to act when `yas/trigger-key' does *not* expand a snippet.
320 - `call-other-command' means try to temporarily disable YASnippet
321 and call the next command bound to `yas/trigger-key'.
323 - nil or the symbol `return-nil' mean do nothing. (and
324 `yas/expand-returns' nil)
326 - A lisp form (apply COMMAND . ARGS) means interactively call
327 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
328 with ARGS as arguments."
329 :type '(choice (const :tag "Call previous command" call-other-command)
330 (const :tag "Do nothing" return-nil))
333 (defcustom yas/choose-keys-first nil
334 "If non-nil, prompt for snippet key first, then for template.
336 Otherwise prompts for all possible snippet names.
338 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
342 (defcustom yas/choose-tables-first nil
343 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
345 Otherwise, user chooses between the merging together of all
348 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
352 (defcustom yas/use-menu 'abbreviate
353 "Display a YASnippet menu in the menu bar.
355 When non-nil, submenus for each snippet table will be listed
356 under the menu \"Yasnippet\".
358 - If set to `real-modes' only submenus whose name more or less
359 corresponds to a major mode are listed.
361 - If set to `abbreviate', only the current major-mode
362 menu and the modes set in `yas/extra-modes' are listed.
364 Any other non-nil value, every submenu is listed."
365 :type '(choice (const :tag "Full" t)
366 (const :tag "Real modes only" real-modes)
367 (const :tag "Abbreviate" abbreviate))
370 (defcustom yas/trigger-symbol " =>"
371 "The text that will be used in menu to represent the trigger."
375 (defcustom yas/wrap-around-region nil
376 "If non-nil, snippet expansion wraps around selected region.
378 The wrapping occurs just before the snippet's exit marker. This
379 can be overriden on a per-snippet basis."
383 (defcustom yas/good-grace t
384 "If non-nil, don't raise errors in inline elisp evaluation.
386 An error string \"[yas] error\" is returned instead."
390 (defcustom yas/visit-from-menu nil
391 "If non-nil visit snippets's files from menu, instead of expanding them.
393 This cafn only work when snippets are loaded from files."
397 (defcustom yas/expand-only-for-last-commands nil
398 "List of `last-command' values to restrict tab-triggering to, or nil.
400 Leave this set at nil (the default) to be able to trigger an
401 expansion simply by placing the cursor after a valid tab trigger,
402 using whichever commands.
404 Optionallly, set this to something like '(self-insert-command) if
405 you to wish restrict expansion to only happen when the last
406 letter of the snippet tab trigger was typed immediately before
407 the trigger key itself."
408 :type '(repeat function)
411 ;; Only two faces, and one of them shouldn't even be used...
413 (defface yas/field-highlight-face
414 '((t (:inherit 'region)))
415 "The face used to highlight the currently active field of a snippet"
418 (defface yas/field-debug-face
420 "The face used for debugging some overlays normally hidden"
424 ;;; User can also customize the next defvars
425 (defun yas/define-some-keys (keys keymap definition)
426 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
427 (let ((keys (or (and (listp keys) keys)
430 (define-key keymap (read-kbd-macro key) definition))))
433 (let ((map (make-sparse-keymap)))
434 (mapc #'(lambda (binding)
435 (yas/define-some-keys (car binding) map (cdr binding)))
436 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
437 (,yas/prev-field-key . yas/prev-field)
438 ("C-g" . yas/abort-snippet)
439 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
441 "The keymap active while a snippet expansion is in progress.")
443 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
444 "List of character syntaxes used to find a trigger key before point.
445 The list is tried in the order while scanning characters
446 backwards from point. For example, if the list is '(\"w\" \"w_\")
447 first look for trigger keys which are composed exclusively of
448 \"word\"-syntax characters, and then, if that fails, look for
449 keys which are either of \"word\" or \"symbol\"
450 syntax. Triggering after
454 will, according to the \"w\" element first try \"bar\". If that
455 isn't a trigger key, \"foo-bar\" is tried, respecting a second
458 (defvar yas/after-exit-snippet-hook
460 "Hooks to run after a snippet exited.
462 The hooks will be run in an environment where some variables bound to
465 `yas/snippet-beg' : The beginning of the region of the snippet.
467 `yas/snippet-end' : Similar to beg.
469 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
471 (defvar yas/before-expand-snippet-hook
473 "Hooks to run just before expanding a snippet.")
475 (defvar yas/buffer-local-condition
476 '(if (and (or (fourth (syntax-ppss))
477 (fifth (syntax-ppss)))
478 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
479 '(require-snippet-condition . force-in-comment)
481 "Snippet expanding condition.
483 This variable is a lisp form which is evaluated everytime a
484 snippet expansion is attemped:
486 * If it evaluates to nil, no snippets can be expanded.
488 * If it evaluates to the a cons (require-snippet-condition
491 * Snippets bearing no \"# condition:\" directive are not
494 * Snippets bearing conditions that evaluate to nil (or
495 produce an error) won't be onsidered.
497 * If the snippet has a condition that evaluates to non-nil
500 * If REQUIREMENT is t, the snippet is considered
502 * If REQUIREMENT is `eq' RESULT, the snippet is
505 * Otherwise, the snippet is not considered.
507 * If it evaluates to the symbol 'always, all snippets are
508 considered for expansion, regardless of any conditions.
510 * If it evaluates to t or some other non-nil value
512 * Snippet bearing no conditions, or conditions that
513 evaluate to non-nil, are considered for expansion.
515 * Otherwise, the snippet is not considered.
517 Here's an example preventing snippets from being expanded from
518 inside comments, in `python-mode' only, with the exception of
519 snippets returning the symbol 'force-in-comment in their
522 (add-hook 'python-mode-hook
524 (setq yas/buffer-local-condition
525 '(if (python-in-string/comment)
526 '(require-snippet-condition . force-in-comment)
529 The default value is similar, it filters out potential snippet
530 expansions inside comments and string literals, unless the
531 snippet itself contains a condition that returns the symbol
532 `force-in-comment'.")
535 ;;; Internal variables
537 (defvar yas/version "0.7.0")
539 (defvar yas/menu-table (make-hash-table)
540 "A hash table of MAJOR-MODE symbols to menu keymaps.")
542 (defvar yas/known-modes
543 '(ruby-mode rst-mode markdown-mode)
544 "A list of mode which is well known but not part of emacs.")
546 (defvar yas/escaped-characters
547 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
548 "List of characters which *might* need to be escaped.")
550 (defconst yas/field-regexp
551 "${\\([0-9]+:\\)?\\([^}]*\\)}"
552 "A regexp to *almost* recognize a field.")
554 (defconst yas/multi-dollar-lisp-expression-regexp
555 "$+[ \t\n]*\\(([^)]*)\\)"
556 "A regexp to *almost* recognize a \"$(...)\" expression.")
558 (defconst yas/backquote-lisp-expression-regexp
560 "A regexp to recognize a \"`lisp-expression`\" expression." )
562 (defconst yas/transform-mirror-regexp
563 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
564 "A regexp to *almost* recognize a mirror with a transform.")
566 (defconst yas/simple-mirror-regexp
568 "A regexp to recognize a simple mirror.")
570 (defvar yas/snippet-id-seed 0
571 "Contains the next id for a snippet.")
573 (defun yas/snippet-next-id ()
574 (let ((id yas/snippet-id-seed))
575 (incf yas/snippet-id-seed)
581 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
582 (defvar last-buffer-undo-list nil)
584 (defvar yas/minor-mode-menu nil
585 "Holds the YASnippet menu")
587 (defun yas/init-minor-keymap ()
588 (let ((map (make-sparse-keymap)))
589 (easy-menu-define yas/minor-mode-menu
591 "Menu used when YAS/minor-mode is active."
594 ["Expand trigger" yas/expand
595 :help "Possibly expand tab trigger before point"]
596 ["Insert at point..." yas/insert-snippet
597 :help "Prompt for an expandable snippet and expand it at point"]
598 ["New snippet..." yas/new-snippet
599 :help "Create a new snippet in an appropriate directory"]
600 ["Visit snippet file..." yas/visit-snippet-file
601 :help "Prompt for an expandable snippet and find its file"]
602 ["Find snippets..." yas/find-snippets
603 :help "Invoke `find-file' in the appropriate snippet directory"]
605 ("Snippet menu behaviour"
606 ["Visit snippets" (setq yas/visit-from-menu t)
607 :help "Visit snippets from the menu"
608 :active t :style radio :selected yas/visit-from-menu]
609 ["Expand snippets" (setq yas/visit-from-menu nil)
610 :help "Expand snippets from the menu"
611 :active t :style radio :selected (not yas/visit-from-menu)]
613 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
614 :help "Show snippet submenus for modes that appear to be real major modes"
615 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
616 ["Show all modes" (setq yas/use-menu 't)
617 :help "Show one snippet submenu for each loaded table"
618 :active t :style radio :selected (eq yas/use-menu 't)]
619 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
620 :help "Show only snippet submenus for the current active modes"
621 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
623 ["Auto" (setq yas/indent-line 'auto)
624 :help "Indent each line of the snippet with `indent-according-to-mode'"
625 :active t :style radio :selected (eq yas/indent-line 'auto)]
626 ["Fixed" (setq yas/indent-line 'fixed)
627 :help "Indent the snippet to the current column"
628 :active t :style radio :selected (eq yas/indent-line 'fixed)]
629 ["None" (setq yas/indent-line 'none)
630 :help "Don't apply any particular snippet indentation after expansion"
631 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
633 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
634 (not yas/also-auto-indent-first-line))
635 :help "When auto-indenting also, auto indent the first line menu"
636 :active (eq yas/indent-line 'auto)
637 :style toggle :selected yas/also-auto-indent-first-line]
640 ["System X-widget" (setq yas/prompt-functions
642 (remove 'yas/x-prompt
643 yas/prompt-functions)))
644 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
645 :active t :style radio :selected (eq (car yas/prompt-functions)
647 ["Dropdown-list" (setq yas/prompt-functions
648 (cons 'yas/dropdown-prompt
649 (remove 'yas/dropdown-prompt
650 yas/prompt-functions)))
651 :help "Use a special dropdown list"
652 :active t :style radio :selected (eq (car yas/prompt-functions)
653 'yas/dropdown-prompt)]
654 ["Ido" (setq yas/prompt-functions
655 (cons 'yas/ido-prompt
656 (remove 'yas/ido-prompt
657 yas/prompt-functions)))
658 :help "Use an ido-style minibuffer prompt"
659 :active t :style radio :selected (eq (car yas/prompt-functions)
661 ["Completing read" (setq yas/prompt-functions
662 (cons 'yas/completing-prompt
663 (remove 'yas/completing-prompt-prompt
664 yas/prompt-functions)))
665 :help "Use a normal minibuffer prompt"
666 :active t :style radio :selected (eq (car yas/prompt-functions)
667 'yas/completing-prompt-prompt)]
670 ["Wrap region in exit marker"
671 (setq yas/wrap-around-region
672 (not yas/wrap-around-region))
673 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
674 :style toggle :selected yas/wrap-around-region]
675 ["Allow stacked expansions "
676 (setq yas/triggers-in-field
677 (not yas/triggers-in-field))
678 :help "If non-nil allow snippets to be triggered inside other snippet fields"
679 :style toggle :selected yas/triggers-in-field]
680 ["Revive snippets on undo "
681 (setq yas/snippet-revival
682 (not yas/snippet-revival))
683 :help "If non-nil allow snippets to become active again after undo"
684 :style toggle :selected yas/snippet-revival]
687 (not yas/good-grace))
688 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
689 :style toggle :selected yas/good-grace]
692 ["Load snippets..." yas/load-directory
693 :help "Load snippets from a specific directory"]
694 ["Reload everything" yas/reload-all
695 :help "Cleanup stuff, reload snippets, rebuild menus"]
697 :help "Display some information about YASsnippet"]))
698 ;; Now for the stuff that has direct keybindings
700 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
701 (define-key map "\C-c&\C-n" 'yas/new-snippet)
702 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
703 (define-key map "\C-c&\C-f" 'yas/find-snippets)
706 (defvar yas/minor-mode-map (yas/init-minor-keymap)
707 "The keymap used when `yas/minor-mode' is active.")
709 (defun yas/trigger-key-reload (&optional unbind-key)
710 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
712 With optional UNBIND-KEY, try to unbind that key from
713 `yas/minor-mode-map'."
714 (when (and unbind-key
716 (not (string= unbind-key "")))
717 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
718 (when (and yas/trigger-key
719 (stringp yas/trigger-key)
720 (not (string= yas/trigger-key "")))
721 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
723 (defvar yas/tables (make-hash-table)
724 "A hash table of mode symbols to `yas/table' objects.")
726 (defvar yas/parents (make-hash-table)
727 "A hash table of mode symbols do lists of direct parent mode symbols.
729 This list is populated when reading the \".yas-parents\" files
730 found when traversing snippet directories with
731 `yas/load-directory'.
733 There might be additionalal parenting information stored in the
734 `derived-mode-parent' property of some mode symbols, but that is
737 (defvar yas/direct-keymaps (list)
738 "Keymap alist supporting direct snippet keybindings.
740 This variable is is placed in `emulation-mode-map-alists'.
742 Its elements looks like (TABLE-NAME . KEYMAP). They're
743 instantiated on `yas/reload-all' but KEYMAP is added to only when
744 loading snippets. `yas//direct-TABLE-NAME' is then a variable set
745 buffer-locally when entering `yas/minor-mode'. KEYMAP binds all
746 defined direct keybindings to the command
747 `yas/expand-from-keymap' which then which snippet to expand.")
749 (defun yas/direct-keymaps-reload ()
750 "Force reload the direct keybinding for active snippet tables."
752 (setq yas/direct-keymaps nil)
753 (maphash #'(lambda (name table)
754 (push (cons (intern (format "yas//direct-%s" name))
755 (yas/table-direct-keymap table))
759 (defun yas/modes-to-activate ()
760 "Compute list of mode symbols that are active for `yas/expand'
762 (let ((modes-to-activate (list major-mode))
764 (while (setq mode (get mode 'derived-mode-parent))
765 (push mode modes-to-activate))
766 (dolist (mode (yas/extra-modes))
767 (push mode modes-to-activate))
769 (append modes-to-activate
770 (mapcan #'(lambda (mode)
771 (yas/all-parents mode))
772 modes-to-activate)))))
774 (defvar yas/minor-mode-hook nil
775 "Hook run when yas/minor-mode is turned on")
778 (define-minor-mode yas/minor-mode
779 "Toggle YASnippet mode.
781 When YASnippet mode is enabled, the `tas/trigger-key' key expands
782 snippets of code depending on the mode.
784 With no argument, this command toggles the mode.
785 positive prefix argument turns on the mode.
786 Negative prefix argument turns off the mode.
788 You can customize the key through `yas/trigger-key'.
791 \\{yas/minor-mode-map}"
793 ;; The indicator for the mode line.
796 (cond (yas/minor-mode
797 ;; Reload the trigger key
799 (yas/trigger-key-reload)
800 ;; Install the direct keymaps in `emulation-mode-map-alists'
801 ;; (we use `add-hook' even though it's not technically a hook,
802 ;; but it works). Then define variables named after modes to
803 ;; index `yas/direct-keymaps'.
805 ;; Also install the post-command-hook.
807 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
808 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
809 ;; Set the `yas//direct-%s' vars for direct keymap expansion
811 (dolist (mode (yas/modes-to-activate))
812 (let ((name (intern (format "yas//direct-%s" mode))))
813 (set-default name nil)
814 (set (make-local-variable name) t)))
817 (dolist (mode (yas/modes-to-activate))
818 (let ((forms (gethash mode yas/scheduled-jit-loads)))
820 (message "[yas] Loading snippets for %s, just in time: %s!" mode form)
822 (remhash mode yas/scheduled-jit-loads))))
824 ;; Uninstall the direct keymaps and the post-command hook
826 (remove-hook 'post-command-hook 'yas/post-command-handler t)
827 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
830 (defvar yas/dont-activate nil
831 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
833 `yas/minor-mode-on' is usually called by `yas/global-mode' so
834 this effectively lets you define exceptions to the \"global\"
835 behaviour. Can also be a function of zero arguments.")
836 (make-variable-buffer-local 'yas/dont-activate)
838 (defun yas/minor-mode-on ()
839 "Turn on YASnippet minor mode.
841 Do this unless `yas/dont-activate' is truish "
843 (unless (or (minibufferp)
844 (if (functionp yas/dont-activate)
845 (funcall yas/dont-activate)
847 ;; Load all snippets definitions unless we still don't have a
848 ;; root-directory or some snippets have already been loaded.
853 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
857 (defadvice yas/global-mode (before yas/reload-with-jit (arg) activate)
861 ;; explicitly enabling
862 (yas/reload-all 'with-jit))
863 ((not yas/global-mode)
865 (yas/reload-all 'with-jit))))
867 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
870 (defvar yas/font-lock-keywords
871 (append '(("^#.*$" . font-lock-comment-face))
872 lisp-font-lock-keywords
873 lisp-font-lock-keywords-1
874 lisp-font-lock-keywords-2
876 (0 font-lock-keyword-face)
877 (1 font-lock-string-face t))
879 (0 font-lock-keyword-face)
880 (1 font-lock-warning-face t))
881 ("${" font-lock-keyword-face)
882 ("$[0-9]+?" font-lock-preprocessor-face)
883 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
885 (0 font-lock-keyword-face)))))
887 (defun yas/init-major-keymap ()
888 (let ((map (make-sparse-keymap)))
889 (easy-menu-define nil
891 "Menu used when snippet-mode is active."
893 (mapcar #'(lambda (ent)
895 (define-key map (third ent) (second ent)))
896 (vector (first ent) (second ent) t))
898 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
899 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
902 (defvar snippet-mode-map
903 (yas/init-major-keymap)
904 "The keymap used when `snippet-mode' is active")
907 (define-derived-mode snippet-mode text-mode "Snippet"
908 "A mode for editing yasnippets"
909 (setq font-lock-defaults '(yas/font-lock-keywords))
910 (set (make-local-variable 'require-final-newline) nil)
911 (set (make-local-variable 'comment-start) "#")
912 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
916 ;;; Internal structs for template management
918 (defstruct (yas/template (:constructor yas/make-blank-template))
919 "A template for a snippet."
929 group ;; as dictated by the #group: directive or .yas-make-groups
930 perm-group ;; as dictated by `yas/define-menu'
934 (defun yas/populate-template (template &rest args)
935 "Helper function to populate a template with properties"
939 (position (intern (substring (symbol-name (car args)) 1))
940 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
942 (setq args (cddr args)))
945 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
946 "A table to store snippets for a particular mode.
948 Has the following fields:
952 A symbol name normally corresponding to a major mode, but can
953 also be a pseudo major-mode to be referenced in
954 `yas/extra-modes', for example.
958 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
959 a string or a vector, where the former is the snippet's trigger
960 and the latter means it's a direct keybinding. NAMEHASH is yet
961 another hash of (NAME . TEMPLATE) where NAME is the snippet's
962 name and TEMPLATE is a `yas/template' object.
964 `yas/table-direct-keymap'
966 A keymap for the snippets in this table that have direct
967 keybindings. This is kept in sync with the keyhash, i.e., all
968 the elements of the keyhash that are vectors appear here as
969 bindings to `yas/expand-from-keymap'.
973 A hash table mapping snippets uuid's to the same `yas/template'
974 objects. A snippet uuid defaults to the snippet's name.
977 (hash (make-hash-table :test 'equal))
978 (uuidhash (make-hash-table :test 'equal))
980 (direct-keymap (make-sparse-keymap)))
982 (defun yas/get-template-by-uuid (mode uuid)
983 "Find the snippet template in MODE by its UUID."
984 (let* ((table (gethash mode yas/tables mode)))
986 (gethash uuid (yas/table-uuidhash table)))))
988 ;; Apropos storing/updating, this works with two steps:
990 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
993 ;; 2. `yas/add-template' to add the mappings again:
995 ;; Create or index the entry in TABLES's `yas/table-hash'
996 ;; linking KEY to a namehash. That namehash links NAME to
997 ;; TEMPLATE, and is also created a new namehash inside that
1000 (defun yas/remove-template-by-uuid (table uuid)
1001 "Remove from TABLE a template identified by UUID."
1002 (let ((template (gethash uuid (yas/table-uuidhash table))))
1004 (let* ((name (yas/template-name template))
1006 ;; Remove the name from each of the targeted namehashes
1008 (maphash #'(lambda (k v)
1009 (let ((template (gethash name v)))
1011 (eq uuid (yas/template-uuid template)))
1013 (when (zerop (hash-table-count v))
1014 (push k empty-keys)))))
1015 (yas/table-hash table))
1016 ;; Remove the namehashed themselves if they've become empty
1018 (dolist (key empty-keys)
1019 (remhash key (yas/table-hash table)))
1021 ;; Finally, remove the uuid from the uuidhash
1023 (remhash uuid (yas/table-uuidhash table))))))
1026 (defun yas/add-template (table template)
1027 "Store in TABLE the snippet template TEMPLATE.
1029 KEY can be a string (trigger key) of a vector (direct
1031 (let ((name (yas/template-name template))
1032 (key (yas/template-key template))
1033 (keybinding (yas/template-keybinding template))
1034 (menu-binding (car (yas/template-menu-binding-pair template))))
1035 (dolist (k (remove nil (list key keybinding)))
1039 (yas/table-hash table))
1041 (make-hash-table :test 'equal)
1042 (yas/table-hash table))))
1044 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1047 (setf (getf (cdr menu-binding) :keys)
1048 (or (and keybinding (key-description keybinding))
1049 (and key (concat key yas/trigger-symbol))))
1050 (setcar (cdr menu-binding)
1053 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1055 (defun yas/update-template (snippet-table template)
1056 "Add or update TEMPLATE in SNIPPET-TABLE.
1058 Also takes care of adding and updaring to the associated menu."
1059 ;; Remove from table by uuid
1061 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1062 ;; Add to table again
1064 (yas/add-template snippet-table template)
1065 ;; Take care of the menu
1067 (let ((keymap (yas/menu-keymap-get-create snippet-table))
1068 (group (yas/template-group template)))
1069 (when (and yas/use-menu
1071 (not (cdr (yas/template-menu-binding-pair template))))
1072 ;; Remove from menu keymap
1074 (yas/delete-from-keymap keymap (yas/template-uuid template))
1076 ;; Add necessary subgroups as necessary.
1078 (dolist (subgroup group)
1079 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1080 (unless (and subgroup-keymap
1081 (keymapp subgroup-keymap))
1082 (setq subgroup-keymap (make-sparse-keymap))
1083 (define-key keymap (vector (make-symbol subgroup))
1084 `(menu-item ,subgroup ,subgroup-keymap)))
1085 (setq keymap subgroup-keymap)))
1087 ;; Add this entry to the keymap
1089 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1090 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1092 (defun yas/namehash-templates-alist (namehash)
1094 (maphash #'(lambda (k v)
1095 (push (cons k v) alist))
1099 (defun yas/fetch (table key)
1100 "Fetch templates in TABLE by KEY.
1102 Return a list of cons (NAME . TEMPLATE) where NAME is a
1103 string and TEMPLATE is a `yas/template' structure."
1104 (let* ((keyhash (yas/table-hash table))
1105 (namehash (and keyhash (gethash key keyhash))))
1107 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1110 ;;; Filtering/condition logic
1112 (defun yas/eval-condition (condition)
1119 (message (format "[yas] error in condition evaluation: %s"
1120 (error-message-string err)))
1124 (defun yas/filter-templates-by-condition (templates)
1125 "Filter the templates using the applicable condition.
1127 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1128 string and TEMPLATE is a `yas/template' structure.
1130 This function implements the rules described in
1131 `yas/buffer-local-condition'. See that variables documentation."
1132 (let ((requirement (yas/require-template-specific-condition-p)))
1133 (if (eq requirement 'always)
1135 (remove-if-not #'(lambda (pair)
1136 (yas/template-can-expand-p
1137 (yas/template-condition (cdr pair)) requirement))
1140 (defun yas/require-template-specific-condition-p ()
1141 "Decides if this buffer requests/requires snippet-specific
1142 conditions to filter out potential expansions."
1143 (if (eq 'always yas/buffer-local-condition)
1145 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1146 (yas/eval-condition yas/buffer-local-condition))
1147 yas/buffer-local-condition)))
1148 (when local-condition
1149 (if (eq local-condition t)
1151 (and (consp local-condition)
1152 (eq 'require-snippet-condition (car local-condition))
1153 (symbolp (cdr local-condition))
1154 (cdr local-condition)))))))
1156 (defun yas/template-can-expand-p (condition requirement)
1157 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1158 (let* ((result (or (null condition)
1159 (yas/eval-condition condition))))
1160 (cond ((eq requirement t)
1163 (eq requirement result)))))
1165 (defun yas/all-parents (mode)
1166 "Returns a list of all parent modes of MODE"
1167 (let ((parents (gethash mode yas/parents)))
1169 (mapcan #'yas/all-parents parents))))
1171 (defun yas/table-templates (table)
1174 (maphash #'(lambda (key namehash)
1175 (maphash #'(lambda (name template)
1176 (push (cons name template) acc))
1178 (yas/table-hash table))
1179 (yas/filter-templates-by-condition acc))))
1181 (defun yas/current-key ()
1182 "Get the key under current position. A key is used to find
1183 the template of a snippet in the current snippet-table."
1184 (let ((start (point))
1186 (syntaxes yas/key-syntaxes)
1190 (while (and (not done) syntaxes)
1191 (setq syntax (car syntaxes))
1192 (setq syntaxes (cdr syntaxes))
1194 (skip-syntax-backward syntax)
1195 (setq start (point)))
1197 (mapcan #'(lambda (table)
1198 (yas/fetch table (buffer-substring-no-properties start end)))
1199 (yas/get-snippet-tables)))
1208 (defun yas/table-all-keys (table)
1211 (maphash #'(lambda (key namehash)
1212 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1214 (yas/table-hash table))
1218 ;;; Internal functions
1220 (defun yas/real-mode? (mode)
1221 "Try to find out if MODE is a real mode. The MODE bound to
1222 a function (like `c-mode') is considered real mode. Other well
1223 known mode like `ruby-mode' which is not part of Emacs might
1224 not bound to a function until it is loaded. So yasnippet keeps
1225 a list of modes like this to help the judgement."
1227 (find mode yas/known-modes)))
1229 (defun yas/eval-lisp (form)
1230 "Evaluate FORM and convert the result to string."
1231 (let ((retval (catch 'yas/exception
1237 (let ((result (eval form)))
1239 (format "%s" result))))))
1240 (error (if yas/good-grace
1241 (format "[yas] elisp error! %s" (error-message-string err))
1242 (error (format "[yas] elisp error: %s"
1243 (error-message-string err)))))))))
1244 (when (and (consp retval)
1245 (eq 'yas/exception (car retval)))
1246 (error (cdr retval)))
1249 (defun yas/eval-lisp-no-saves (form)
1252 (error (if yas/good-grace
1253 (format "[yas] elisp error! %s" (error-message-string err))
1254 (error (format "[yas] elisp error: %s"
1255 (error-message-string err)))))))
1257 (defun yas/read-lisp (string &optional nil-on-error)
1258 "Read STRING as a elisp expression and return it.
1260 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1261 return an expression that when evaluated will issue an error."
1264 (error (and (not nil-on-error)
1265 `(error (error-message-string ,err))))))
1267 (defun yas/read-keybinding (keybinding)
1268 "Read KEYBINDING as a snippet keybinding, return a vector."
1269 (when (and keybinding
1270 (not (string-match "keybinding" keybinding)))
1272 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1274 (read-kbd-macro keybinding 'need-vector))))
1277 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1278 keybinding (error-message-string err))
1281 (defvar yas/extra-modes nil
1282 "If non-nil, also lookup snippets for this/these modes.
1284 Can be a symbol or a list of symbols.
1286 This variable probably makes more sense as buffer-local, so
1287 ensure your use `make-local-variable' when you set it.")
1288 (defun yas/extra-modes ()
1289 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1290 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1292 (defun yas/table-get-create (mode)
1293 "Get or create the snippet table corresponding to MODE."
1294 (let ((table (gethash mode
1297 (setq table (yas/make-snippet-table (symbol-name mode)))
1298 (puthash mode table yas/tables)
1299 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1300 (yas/table-direct-keymap table)))
1303 (defun yas/get-snippet-tables ()
1304 "Get snippet tables for current buffer.
1306 Return a list of `yas/table' objects. The list of modes to
1307 consider is returned by `yas/modes-to-activate'"
1309 (mapcar #'(lambda (mode-name)
1310 (gethash mode-name yas/tables))
1311 (yas/modes-to-activate))))
1313 (defun yas/menu-keymap-get-create (table)
1314 "Get or create the main menu keymap correspondong to MODE.
1316 This may very well create a plethora of menu keymaps and arrange
1317 them in all `yas/menu-table'"
1318 (let* ((mode (intern (yas/table-name table)))
1319 (menu-keymap (or (gethash mode yas/menu-table)
1320 (puthash mode (make-sparse-keymap) yas/menu-table)))
1321 (parents (yas/table-parents table)))
1322 (mapc #'yas/menu-keymap-get-create parents)
1323 (define-key yas/minor-mode-menu (vector mode)
1324 `(menu-item ,(symbol-name mode) ,menu-keymap
1325 :visible (yas/show-menu-p ',mode)))
1328 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1329 ;;; Template-related and snippet loading functions
1331 (defun yas/parse-template (&optional file)
1332 "Parse the template in the current buffer.
1334 Optional FILE is the absolute file name of the file being
1337 Optional GROUP is the group where the template is to go,
1338 otherwise we attempt to calculate it from FILE.
1340 Return a snippet-definition, i.e. a list
1342 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1344 If the buffer contains a line of \"# --\" then the contents above
1345 this line are ignored. Directives can set most of these with the syntax:
1347 # directive-name : directive-value
1349 Here's a list of currently recognized directives:
1360 (goto-char (point-min))
1361 (let* ((type 'snippet)
1363 (file-name-nondirectory file)))
1369 (yas/calculate-group file)))
1373 (if (re-search-forward "^# --\n" nil t)
1374 (progn (setq template
1375 (buffer-substring-no-properties (point)
1377 (setq bound (point))
1378 (goto-char (point-min))
1379 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1380 (when (string= "uuid" (match-string-no-properties 1))
1381 (setq uuid (match-string-no-properties 2)))
1382 (when (string= "type" (match-string-no-properties 1))
1383 (setq type (if (string= "command" (match-string-no-properties 2))
1386 (when (string= "key" (match-string-no-properties 1))
1387 (setq key (match-string-no-properties 2)))
1388 (when (string= "name" (match-string-no-properties 1))
1389 (setq name (match-string-no-properties 2)))
1390 (when (string= "condition" (match-string-no-properties 1))
1391 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1392 (when (string= "group" (match-string-no-properties 1))
1393 (setq group (match-string-no-properties 2)))
1394 (when (string= "expand-env" (match-string-no-properties 1))
1395 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1397 (when (string= "binding" (match-string-no-properties 1))
1398 (setq binding (match-string-no-properties 2)))))
1400 (buffer-substring-no-properties (point-min) (point-max))))
1401 (unless (or key binding)
1402 (setq key (and file (file-name-nondirectory file))))
1403 (when (eq type 'command)
1404 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1406 (setq group (split-string group "\\.")))
1407 (list key template name condition group expand-env file binding uuid)))
1409 (defun yas/calculate-group (file)
1410 "Calculate the group for snippet file path FILE."
1411 (let* ((dominating-dir (locate-dominating-file file
1412 ".yas-make-groups"))
1413 (extra-path (and dominating-dir
1414 (replace-regexp-in-string (concat "^"
1415 (expand-file-name dominating-dir))
1417 (expand-file-name file))))
1418 (extra-dir (and extra-path
1419 (file-name-directory extra-path)))
1420 (group (and extra-dir
1421 (replace-regexp-in-string "/"
1423 (directory-file-name extra-dir)))))
1426 (defun yas/subdirs (directory &optional filep)
1427 "Return subdirs or files of DIRECTORY according to FILEP."
1428 (remove-if (lambda (file)
1429 (or (string-match "^\\."
1430 (file-name-nondirectory file))
1431 (string-match "^#.*#$"
1432 (file-name-nondirectory file))
1434 (file-name-nondirectory file))
1436 (file-directory-p file)
1437 (not (file-directory-p file)))))
1438 (directory-files directory t)))
1440 (defun yas/make-menu-binding (template)
1441 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1442 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1444 (defun yas/expand-or-visit-from-menu (mode uuid)
1445 (let* ((table (yas/table-get-create mode))
1446 (yas/current-template (and table
1447 (gethash uuid (yas/table-uuidhash table)))))
1448 (when yas/current-template
1449 (if yas/visit-from-menu
1450 (yas/visit-snippet-file-1 yas/current-template)
1451 (let ((where (if (region-active-p)
1452 (cons (region-beginning) (region-end))
1453 (cons (point) (point)))))
1454 (yas/expand-snippet (yas/template-content yas/current-template)
1457 (yas/template-expand-env yas/current-template)))))))
1459 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1460 ;; Popping up for keys and templates
1462 (defvar yas/x-pretty-prompt-templates nil
1463 "If non-nil, attempt to prompt for templates like TextMate.")
1466 (defun yas/prompt-for-template (templates &optional prompt)
1467 "Interactively choose a template from the list TEMPLATES.
1469 TEMPLATES is a list of `yas/template'."
1472 (sort templates #'(lambda (t1 t2)
1473 (< (length (yas/template-name t1))
1474 (length (yas/template-name t2))))))
1475 (if yas/x-pretty-prompt-templates
1476 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1477 (some #'(lambda (fn)
1478 (funcall fn (or prompt "Choose a snippet: ")
1480 #'yas/template-name))
1481 yas/prompt-functions))))
1483 (defun yas/prompt-for-keys (keys &optional prompt)
1484 "Interactively choose a template key from the list KEYS."
1486 (some #'(lambda (fn)
1487 (funcall fn (or prompt "Choose a snippet key: ") keys))
1488 yas/prompt-functions)))
1490 (defun yas/prompt-for-table (tables &optional prompt)
1492 (some #'(lambda (fn)
1493 (funcall fn (or prompt "Choose a snippet table: ")
1496 yas/prompt-functions)))
1498 (defun yas/x-prompt (prompt choices &optional display-fn)
1499 "Display choices in a x-window prompt."
1500 ;; FIXME: HACK: if we notice that one of the objects in choices is
1501 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1503 ;; This would be better implemented by passing CHOICES as a
1504 ;; strucutred tree rather than a list. Modifications would go as far
1505 ;; up as `yas/all-templates' I think.
1507 (when (and window-system choices)
1509 (let (menu d) ;; d for display
1511 (setq d (or (and display-fn (funcall display-fn c))
1514 (push (cons (concat " " d) c) menu))
1516 (push (car d) menu))))
1517 (setq menu (list prompt (push "title" menu)))
1518 (x-popup-menu (if (fboundp 'posn-at-point)
1519 (let ((x-y (posn-x-y (posn-at-point (point)))))
1520 (list (list (+ (car x-y) 10)
1528 (defun yas/x-pretty-prompt-templates (prompt templates)
1529 "Display TEMPLATES, grouping neatly by table name."
1530 (let ((pretty-alist (list))
1534 (dolist (tl templates)
1535 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1536 (setq more-than-one-table (> (length pretty-alist) 1))
1537 (setq prefix (if more-than-one-table
1539 (dolist (table-and-templates pretty-alist)
1540 (when (cdr table-and-templates)
1541 (if more-than-one-table
1542 (push (yas/table-name (car table-and-templates)) menu))
1543 (dolist (template (cdr table-and-templates))
1544 (push (cons (concat prefix (yas/template-name template))
1546 (setq menu (nreverse menu))
1547 (or (x-popup-menu (if (fboundp 'posn-at-point)
1548 (let ((x-y (posn-x-y (posn-at-point (point)))))
1549 (list (list (+ (car x-y) 10)
1553 (list prompt (push "title" menu)))
1556 (defun yas/ido-prompt (prompt choices &optional display-fn)
1557 (when (featurep 'ido)
1558 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1560 (eval-when-compile (require 'dropdown-list nil t))
1561 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1562 (when (featurep 'dropdown-list)
1563 (let (formatted-choices
1567 (dolist (choice choices)
1568 (setq d (or (and display-fn (funcall display-fn choice))
1571 (push d formatted-choices)
1572 (push choice filtered-choices)))
1574 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1576 (nth n filtered-choices)
1579 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1580 (let (formatted-choices
1584 (completion-fn (or completion-fnn
1585 #'completing-read)))
1586 (dolist (choice choices)
1587 (setq d (or (and display-fn (funcall display-fn choice))
1590 (push d formatted-choices)
1591 (push choice filtered-choices)))
1592 (setq chosen (and formatted-choices
1593 (funcall completion-fn prompt
1600 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1602 (defun yas/no-prompt (prompt choices &optional display-fn)
1605 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1606 ;; Loading snippets from files
1608 (defun yas/load-directory-1 (directory mode-sym &optional no-compiled-snippets)
1609 "Recursively load snippet templates from DIRECTORY."
1610 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1611 ;; Load .yas-setup.el files wherever we find them
1613 (load (expand-file-name ".yas-setup" directory) 'noerror)
1614 (if (and (not no-compiled-snippets)
1615 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror))
1616 (message "[yas] Loading much faster .yas-compiled-snippets from %s" directory)
1617 (let* ((default-directory directory)
1619 ;; load the snippet files
1622 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1623 (when (file-readable-p file)
1624 (insert-file-contents file nil nil nil t)
1625 (push (yas/parse-template file)
1627 (when (or snippet-defs
1628 (cdr major-mode-and-parents))
1629 (yas/define-snippets mode-sym
1631 ;; now recurse to a lower level
1633 (dolist (subdir (yas/subdirs directory))
1634 (yas/load-directory-1 subdir
1638 (defun yas/load-directory (top-level-dir)
1639 "Load snippet definition from directory hierarchy under TOP-LEVEL-DIR.
1641 Below TOP-LEVEL-DIR., each directory is a mode name."
1642 (interactive "DSelect the root directory: ")
1643 (unless (file-directory-p top-level-dir)
1644 (error "%s is not a directory" top-level-dir))
1645 (unless yas/snippet-dirs
1646 (setq yas/snippet-dirs top-level-dir))
1647 (dolist (dir (yas/subdirs top-level-dir))
1648 (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents
1649 (concat dir "/dummy")))
1650 (mode-sym (car major-mode-and-parents))
1651 (parents (cdr major-mode-and-parents)))
1652 (puthash mode-sym (remove-duplicates
1654 (gethash mode-sym yas/parents)))
1656 (yas/schedule-jit mode-sym
1657 `(yas/load-directory-1 ,dir
1659 (when (interactive-p)
1660 (message "[yas] Loaded snippets from %s." top-level-dir)))
1662 (defun yas/load-snippet-dirs ()
1663 "Reload the directories listed in `yas/snippet-dirs' or
1664 prompt the user to select one."
1666 (if yas/snippet-dirs
1667 (dolist (directory (reverse (yas/snippet-dirs)))
1668 (condition-case oops
1670 (yas/load-directory directory)
1671 (message "[yas] Loaded %s" directory))
1672 (error (push oops errors)
1673 (message "[yas] Check your `yas/snippet-dirs': %s" (second oops)))))
1674 (call-interactively 'yas/load-directory))
1677 (defun yas/reload-all (&optional with-jit)
1678 "Reload all snippets and rebuild the YASnippet menu. "
1681 ;; Empty all snippet tables, parenting info and all menu tables
1683 (setq yas/tables (make-hash-table))
1684 (setq yas/parents (make-hash-table))
1685 (setq yas/menu-table (make-hash-table))
1687 ;; Cancel all pending 'yas/scheduled-jit-loads'
1689 (setq yas/scheduled-jit-loads (make-hash-table))
1691 ;; Init the `yas/minor-mode-map', taking care not to break the
1694 (setf (cdr yas/minor-mode-map)
1695 (cdr (yas/init-minor-keymap)))
1697 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1698 ;; the user to select one.
1700 (setq errors (yas/load-snippet-dirs))
1701 ;; Reload the direct keybindings
1703 (yas/direct-keymaps-reload)
1704 (message "[yas] Reloaded everything...%s." (if errors " (some errors, check *Messages*)" ""))))
1706 (defun yas/quote-string (string)
1707 "Escape and quote STRING.
1708 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1710 (replace-regexp-in-string "[\\\"]"
1715 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1716 ;;; Snippet compilation function
1718 (defun yas/initialize ()
1719 "For backward compatibility, enable `yas/minor-mode' globally"
1720 (yas/global-mode 1))
1722 (defun yas/compile-top-level-dir (top-level-dir)
1723 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR."
1724 (interactive "DTop level snippet directory?")
1725 (dolist (dir (yas/subdirs top-level-dir))
1726 (yas/compile-snippets dir)))
1728 (defun yas/compile-snippets (input-dir &optional output-file)
1729 "Compile snippets files in INPUT-DIR to OUTPUT-FILE file.
1731 Prompts for INPUT-DIR and OUTPUT-FILE if called-interactively"
1732 (interactive (let* ((input-dir (read-directory-name "Snippet dir "))
1733 (output-file (let ((ido-everywhere nil))
1734 (read-file-name "Output file "
1736 ".yas-compiled-snippets.el"
1738 (list input-dir output-file)))
1739 (let ((default-directory input-dir))
1740 (with-temp-file (setq output-file (or output-file ".yas-compiled-snippets.el"))
1741 (flet ((yas/define-snippets
1743 (insert (format ";;; %s - automatically compiled snippets for `%s' , do not edit!\n"
1744 (file-name-nondirectory output-file) mode))
1746 (let ((literal-snippets (list)))
1747 (dolist (snippet snippets)
1748 (let ((key (first snippet))
1749 (template-content (second snippet))
1750 (name (third snippet))
1751 (condition (fourth snippet))
1752 (group (fifth snippet))
1753 (expand-env (sixth snippet))
1754 (file nil) ;; (seventh snippet)) ;; omit on purpose
1755 (binding (eighth snippet))
1756 (uuid (ninth snippet)))
1767 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1769 (insert (format ";;; %s - automatically compiled snippets for `%s' end here\n"
1770 (file-name-nondirectory output-file) mode))
1772 (yas/load-directory-1 input-dir nil 'no-compiled-snippets))))
1774 (if (and (called-interactively-p)
1775 (yes-or-no-p (format "Open the resulting file (%s)? "
1776 (expand-file-name output-file))))
1777 (find-file-other-window output-file)))
1783 (defvar yas/scheduled-jit-loads (make-hash-table)
1784 "Alist of mode-symbols to forms to be evaled when `yas/minor-mode' kicks in.")
1786 (defun yas/schedule-jit (mode form)
1789 (gethash mode yas/scheduled-jit-loads))
1790 yas/scheduled-jit-loads))
1793 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1794 ;;; Some user level functions
1799 (message (concat "yasnippet (version "
1801 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1803 (defun yas/define-snippets (mode snippets)
1804 "Define SNIPPETS for MODE.
1806 SNIPPETS is a list of snippet definitions, each taking the
1809 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1811 Within these, only KEY and TEMPLATE are actually mandatory.
1813 TEMPLATE might be a lisp form or a string, depending on whether
1814 this is a snippet or a snippet-command.
1816 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1817 been `yas/read-lisp'-ed and will eventually be
1820 The remaining elements are strings.
1822 FILE is probably of very little use if you're programatically
1825 UUID is the snippets \"unique-id\". Loading a second snippet file
1826 with the same uuid replaced the previous snippet.
1828 You can use `yas/parse-template' to return such lists based on
1829 the current buffers contents."
1830 (let ((snippet-table (yas/table-get-create mode))
1832 (dolist (snippet snippets)
1833 (setq template (yas/define-snippets-1 snippet
1837 (defun yas/define-snippets-1 (snippet snippet-table)
1838 "Helper for `yas/define-snippets'."
1839 ;; X) Calculate some more defaults on the values returned by
1840 ;; `yas/parse-template'.
1842 (let* ((file (seventh snippet))
1844 (name (or (third snippet)
1846 (file-name-directory file))))
1847 (condition (fourth snippet))
1848 (group (fifth snippet))
1849 (keybinding (yas/read-keybinding (eighth snippet)))
1850 (uuid (or (ninth snippet)
1852 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1853 (yas/make-blank-template))))
1854 ;; X) populate the template object
1856 (yas/populate-template template
1857 :table snippet-table
1859 :content (second snippet)
1862 :condition condition
1863 :expand-env (sixth snippet)
1864 :file (seventh snippet)
1865 :keybinding keybinding
1867 ;; X) Update this template in the appropriate table. This step
1868 ;; also will take care of adding the key indicators in the
1869 ;; templates menu entry, if any
1871 (yas/update-template snippet-table template)
1872 ;; X) Return the template
1877 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1878 "Get TEMPLATE's menu binding or assign it a new one."
1879 (or (yas/template-menu-binding-pair template)
1880 (let ((key (yas/template-key template))
1881 (keybinding (yas/template-keybinding template)))
1882 (setf (yas/template-menu-binding-pair template)
1883 (cons `(menu-item ,(or (yas/template-name template)
1884 (yas/template-uuid template))
1885 ,(yas/make-menu-binding template)
1889 (defun yas/show-menu-p (mode)
1890 (cond ((eq yas/use-menu 'abbreviate)
1892 (mapcar #'(lambda (table)
1893 (intern (yas/table-name table)))
1894 (yas/get-snippet-tables))))
1895 ((eq yas/use-menu 'real-modes)
1896 (yas/real-mode? mode))
1900 (defun yas/delete-from-keymap (keymap uuid)
1901 "Recursively delete items with UUID from KEYMAP and its submenus."
1903 ;; XXX: This used to skip any submenus named \"parent mode\"
1905 ;; First of all, recursively enter submenus, i.e. the tree is
1906 ;; searched depth first so that stale submenus can be found in the
1909 (mapc #'(lambda (item)
1910 (when (and (listp (cdr item))
1911 (keymapp (third (cdr item))))
1912 (yas/delete-from-keymap (third (cdr item)) uuid)))
1914 ;; Set the uuid entry to nil
1916 (define-key keymap (vector (make-symbol uuid)) nil)
1917 ;; Destructively modify keymap
1919 (setcdr keymap (delete-if #'(lambda (item)
1920 (or (null (cdr item))
1921 (and (keymapp (third (cdr item)))
1922 (null (cdr (third (cdr item)))))))
1925 (defun yas/define-menu (mode menu omit-items)
1926 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
1928 MENU is a list, its elements can be:
1930 - (yas/item UUID) : Creates an entry the snippet identified with
1931 UUID. The menu entry for a snippet thus identified is
1932 permanent, i.e. it will never move in the menu.
1934 - (yas/separator) : Creates a separator
1936 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
1937 SUBMENU has the same form as MENU. NAME is also added to the
1938 list of groups of the snippets defined thereafter.
1940 OMIT-ITEMS is a list of snippet uuid's that will always be
1941 ommited from MODE's menu, even if they're manually loaded.
1943 (let* ((table (yas/table-get-create mode))
1944 (hash (yas/table-uuidhash table)))
1945 (yas/define-menu-1 table
1946 (yas/menu-keymap-get-create table)
1949 (dolist (uuid omit-items)
1950 (let ((template (or (gethash uuid hash)
1951 (yas/populate-template (puthash uuid
1952 (yas/make-blank-template)
1956 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
1958 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
1959 (dolist (e (reverse menu))
1960 (cond ((eq (first e) 'yas/item)
1961 (let ((template (or (gethash (second e) uuidhash)
1962 (yas/populate-template (puthash (second e)
1963 (yas/make-blank-template)
1966 :perm-group group-list
1967 :uuid (second e)))))
1968 (define-key keymap (vector (gensym))
1969 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
1970 ((eq (first e) 'yas/submenu)
1971 (let ((subkeymap (make-sparse-keymap)))
1972 (define-key keymap (vector (gensym))
1973 `(menu-item ,(second e) ,subkeymap))
1974 (yas/define-menu-1 table
1978 (append group-list (list (second e))))))
1979 ((eq (first e) 'yas/separator)
1980 (define-key keymap (vector (gensym))
1981 '(menu-item "----")))
1983 (message "[yas] Don't know anything about menu entry %s" (first e))))))
1985 (defun yas/define (mode key template &optional name condition group)
1986 "Define a snippet. Expanding KEY into TEMPLATE.
1988 NAME is a description to this template. Also update the menu if
1989 `yas/use-menu' is `t'. CONDITION is the condition attached to
1990 this snippet. If you attach a condition to a snippet, then it
1991 will only be expanded when the condition evaluated to non-nil."
1992 (yas/define-snippets mode
1993 (list (list key template name condition group))))
1995 (defun yas/hippie-try-expand (first-time?)
1996 "Integrate with hippie expand. Just put this function in
1997 `hippie-expand-try-functions-list'."
1998 (if (not first-time?)
1999 (let ((yas/fallback-behavior 'return-nil))
2005 ;;; Apropos condition-cache:
2010 (defvar yas/condition-cache-timestamp nil)
2011 (defmacro yas/define-condition-cache (func doc &rest body)
2012 "Define a function FUNC with doc DOC and body BODY, BODY is
2013 executed at most once every snippet expansion attempt, to check
2014 expansion conditions.
2016 It doesn't make any sense to call FUNC programatically."
2017 `(defun ,func () ,(if (and doc
2020 "\n\nFor use in snippets' conditions. Within each
2021 snippet-expansion routine like `yas/expand', computes actual
2022 value for the first time then always returns a cached value.")
2023 (setq body (cons doc body))
2025 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2026 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2027 (cdr timestamp-and-value)
2028 (let ((new-value (progn
2031 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2034 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2035 (defun yas/expand-from-trigger-key (&optional field)
2036 "Expand a snippet before point.
2038 If no snippet expansion is possible, fall back to the behaviour
2039 defined in `yas/fallback-behavior'.
2041 Optional argument FIELD is for non-interactive use and is an
2042 object satisfying `yas/field-p' to restrict the expansion to."
2044 (setq yas/condition-cache-timestamp (current-time))
2045 (let (templates-and-pos)
2046 (unless (and yas/expand-only-for-last-commands
2047 (not (member last-command yas/expand-only-for-last-commands)))
2048 (setq templates-and-pos (if field
2050 (narrow-to-region (yas/field-start field)
2051 (yas/field-end field))
2053 (yas/current-key))))
2054 (if (and templates-and-pos
2055 (first templates-and-pos))
2056 (yas/expand-or-prompt-for-template (first templates-and-pos)
2057 (second templates-and-pos)
2058 (third templates-and-pos))
2059 (yas/fallback 'trigger-key))))
2061 (defun yas/expand-from-keymap ()
2062 "Directly expand some snippets, searching `yas/direct-keymaps'.
2064 If expansion fails, execute the previous binding for this key"
2066 (setq yas/condition-cache-timestamp (current-time))
2067 (let* ((yas/prefix current-prefix-arg)
2068 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2069 universal-argument-num-events
2071 (templates (mapcan #'(lambda (table)
2072 (yas/fetch table vec))
2073 (yas/get-snippet-tables))))
2075 (yas/expand-or-prompt-for-template templates)
2076 (let ((yas/fallback-behavior 'call-other-command))
2079 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2080 "Expand one of TEMPLATES from START to END.
2082 Prompt the user if TEMPLATES has more than one element, else
2083 expand immediately. Common gateway for
2084 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2085 (let ((yas/current-template (or (and (rest templates) ;; more than one
2086 (yas/prompt-for-template (mapcar #'cdr templates)))
2088 (when yas/current-template
2089 (yas/expand-snippet (yas/template-content yas/current-template)
2092 (yas/template-expand-env yas/current-template)))))
2094 (defun yas/fallback (&optional from-trigger-key-p)
2095 "Fallback after expansion has failed.
2097 Common gateway for `yas/expand-from-trigger-key' and
2098 `yas/expand-from-keymap'."
2099 (cond ((eq yas/fallback-behavior 'return-nil)
2102 ((eq yas/fallback-behavior 'call-other-command)
2103 (let* ((yas/minor-mode nil)
2104 (yas/direct-keymaps nil)
2105 (keys-1 (this-command-keys-vector))
2106 (keys-2 (and yas/trigger-key
2108 (stringp yas/trigger-key)
2109 (read-kbd-macro yas/trigger-key)))
2110 (command-1 (and keys-1 (key-binding keys-1)))
2111 (command-2 (and keys-2 (key-binding keys-2)))
2112 ;; An (ugly) safety: prevents infinite recursion of
2113 ;; yas/expand* calls.
2114 (command (or (and (symbolp command-1)
2115 (not (string-match "yas/expand" (symbol-name command-1)))
2117 (and (symbolp command-2)
2119 (when (and (commandp command)
2120 (not (string-match "yas/expand" (symbol-name command))))
2121 (setq this-command command)
2122 (call-interactively command))))
2123 ((and (listp yas/fallback-behavior)
2124 (cdr yas/fallback-behavior)
2125 (eq 'apply (car yas/fallback-behavior)))
2126 (if (cddr yas/fallback-behavior)
2127 (apply (cadr yas/fallback-behavior)
2128 (cddr yas/fallback-behavior))
2129 (when (commandp (cadr yas/fallback-behavior))
2130 (setq this-command (cadr yas/fallback-behavior))
2131 (call-interactively (cadr yas/fallback-behavior)))))
2133 ;; also return nil if all the other fallbacks have failed
2138 ;;; Snippet development
2140 (defun yas/all-templates (tables)
2141 "Return all snippet tables applicable for the current buffer.
2143 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2144 `yas/buffer-local-condition'"
2145 (when yas/choose-tables-first
2146 (setq tables (list (yas/prompt-for-table tables))))
2148 (if yas/choose-keys-first
2149 (let ((key (yas/prompt-for-keys
2150 (mapcan #'yas/table-all-keys tables))))
2152 (mapcan #'(lambda (table)
2153 (yas/fetch table key))
2155 (remove-duplicates (mapcan #'yas/table-templates tables)
2158 (defun yas/insert-snippet (&optional no-condition)
2159 "Choose a snippet to expand, pop-up a list of choices according
2160 to `yas/prompt-function'.
2162 With prefix argument NO-CONDITION, bypass filtering of snippets
2165 (setq yas/condition-cache-timestamp (current-time))
2166 (let* ((yas/buffer-local-condition (or (and no-condition
2168 yas/buffer-local-condition))
2169 (templates (yas/all-templates (yas/get-snippet-tables)))
2170 (yas/current-template (and templates
2171 (or (and (rest templates) ;; more than one template for same key
2172 (yas/prompt-for-template templates))
2174 (where (if (region-active-p)
2175 (cons (region-beginning) (region-end))
2176 (cons (point) (point)))))
2177 (if yas/current-template
2178 (yas/expand-snippet (yas/template-content yas/current-template)
2181 (yas/template-expand-env yas/current-template))
2182 (message "[yas] No snippets can be inserted here!"))))
2184 (defun yas/visit-snippet-file ()
2185 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2187 Only success if selected snippet was loaded from a file. Put the
2188 visited file in `snippet-mode'."
2190 (let* ((yas/buffer-local-condition 'always)
2191 (templates (yas/all-templates (yas/get-snippet-tables)))
2192 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2193 (template (and templates
2194 (or (yas/prompt-for-template templates
2195 "Choose a snippet template to edit: ")
2199 (yas/visit-snippet-file-1 template)
2200 (message "No snippets tables active!"))))
2202 (defun yas/visit-snippet-file-1 (template)
2203 (let ((file (yas/template-file template)))
2204 (cond ((and file (file-readable-p file))
2205 (find-file-other-window file)
2207 (set (make-local-variable 'yas/editing-template) template))
2209 (message "Original file %s no longer exists!" file))
2211 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2212 (let ((type 'snippet))
2213 (when (listp (yas/template-content template))
2214 (insert (format "# type: command\n"))
2215 (setq type 'command))
2216 (insert (format "# key: %s\n" (yas/template-key template)))
2217 (insert (format "# name: %s\n" (yas/template-name template)))
2218 (when (yas/template-keybinding template)
2219 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2220 (when (yas/template-expand-env template)
2221 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2222 (when (yas/template-condition template)
2223 (insert (format "# condition: %s\n" (yas/template-condition template))))
2225 (insert (if (eq type 'command)
2226 (pp-to-string (yas/template-content template))
2227 (yas/template-content template))))
2229 (set (make-local-variable 'yas/editing-template) template)))))
2231 (defun yas/guess-snippet-directories-1 (table)
2232 "Guesses possible snippet subdirectories for TABLE."
2233 (cons (yas/table-name table)
2234 (mapcan #'(lambda (parent)
2235 (yas/guess-snippet-directories-1
2237 (yas/table-parents table))))
2239 (defun yas/guess-snippet-directories (&optional table)
2240 "Try to guess suitable directories based on the current active
2241 tables (or optional TABLE).
2243 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2244 `yas/table' object and DIRS is a list of all possible directories
2245 where snippets of table might exist."
2246 (let ((main-dir (replace-regexp-in-string
2248 (or (first (or (yas/snippet-dirs)
2249 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2250 (tables (or (and table
2252 (yas/get-snippet-tables))))
2253 ;; HACK! the snippet table created here is actually registered!
2255 (unless (or table (gethash major-mode yas/tables))
2256 (push (yas/table-get-create major-mode)
2259 (mapcar #'(lambda (table)
2261 (mapcar #'(lambda (subdir)
2262 (concat main-dir "/" subdir))
2263 (yas/guess-snippet-directories-1 table))))
2266 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2267 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2268 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2269 (let ((candidate (first (cdr table-and-dirs))))
2270 (unless (file-writable-p (file-name-directory candidate))
2271 (error "[yas] %s is not writable." candidate))
2272 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2274 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2278 (or main-table-string
2280 (yas/table-name (car table-and-dirs))))
2282 (make-directory candidate 'also-make-parents)
2283 ;; create the .yas-parents file here...
2286 (defun yas/new-snippet (&optional no-template)
2287 "Pops a new buffer for writing a snippet.
2289 Expands a snippet-writing snippet, unless the optional prefix arg
2290 NO-TEMPLATE is non-nil."
2292 (let ((guessed-directories (yas/guess-snippet-directories)))
2294 (switch-to-buffer "*new snippet*")
2296 (kill-all-local-variables)
2299 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2300 (intern (yas/table-name (car d))))
2301 guessed-directories))
2302 (unless no-template (yas/expand-snippet "\
2303 # -*- mode: snippet -*-
2306 # binding: ${4:direct-keybinding}}${5:
2307 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2312 (defun yas/find-snippets (&optional same-window )
2313 "Find snippet file in guessed current mode's directory.
2315 Calls `find-file' interactively in the guessed directory.
2317 With prefix arg SAME-WINDOW opens the buffer in the same window.
2319 Because snippets can be loaded from many different locations,
2320 this has to guess the correct directory using
2321 `yas/guess-snippet-directories', which returns a list of
2324 If any one of these exists, it is taken and `find-file' is called
2325 there, otherwise, proposes to create the first option returned by
2326 `yas/guess-snippet-directories'."
2328 (let* ((guessed-directories (yas/guess-snippet-directories))
2331 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2333 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2334 (mapcar #'(lambda (table-and-dirs)
2335 (yas/table-name (car table-and-dirs)))
2336 (rest guessed-directories))))
2337 (setq chosen (some #'yas/make-directory-maybe
2338 (rest guessed-directories)))))
2340 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2341 (setq chosen (first (yas/snippet-dirs)))))
2343 (let ((default-directory chosen))
2344 (setq buffer (call-interactively (if same-window
2346 'find-file-other-window)))
2350 (when (eq major-mode 'fundamental-mode)
2352 (message "Could not guess snippet dir!"))))
2354 (defun yas/compute-major-mode-and-parents (file)
2355 "Given FILE, find the nearest snippet directory for a given
2356 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2357 representing one or more of the mode's parents.
2359 Note that MODE-SYM need not be the symbol of a real major mode,
2360 neither do the elements of PARENTS."
2361 (let* ((file-dir (and file
2362 (directory-file-name (or (some #'(lambda (special)
2363 (locate-dominating-file file special))
2367 (directory-file-name (file-name-directory file))))))
2368 (parents-file-name (concat file-dir "/.yas-parents"))
2369 (major-mode-name (and file-dir
2370 (file-name-nondirectory file-dir)))
2371 (major-mode-sym (or (and major-mode-name
2372 (intern major-mode-name))))
2373 (parents (when (file-readable-p parents-file-name)
2377 (insert-file-contents parents-file-name)
2378 (buffer-substring-no-properties (point-min)
2380 (when major-mode-sym
2381 (cons major-mode-sym parents))))
2383 (defvar yas/editing-template nil
2384 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2386 (defvar yas/current-template nil
2387 "Holds the current template being expanded into a snippet.")
2389 (defvar yas/guessed-modes nil
2390 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2392 (defun yas/load-snippet-buffer (&optional kill)
2393 "Parse and load current buffer's snippet definition.
2395 With optional prefix argument KILL quit the window and buffer."
2398 ;; We have `yas/editing-template', this buffer's
2399 ;; content comes from a template which is already loaded and
2400 ;; neatly positioned,...
2402 (yas/editing-template
2403 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2404 (yas/template-table yas/editing-template)))
2405 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2406 ;; value from `yas/compute-major-mode-and-parents'
2409 (unless yas/guessed-modes
2410 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2411 (let* ((prompt (if (and (featurep 'ido)
2413 'ido-completing-read 'completing-read))
2414 (table (yas/table-get-create
2416 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2417 (if yas/guessed-modes
2418 (first yas/guessed-modes)
2420 (mapcar #'symbol-name yas/guessed-modes)
2425 (if (first yas/guessed-modes)
2426 (symbol-name (first yas/guessed-modes))))))))
2427 (set (make-local-variable 'yas/editing-template)
2428 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2430 ;; Now, offer to save this shit iff:
2432 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2433 ;; match this template's file (i.e. this is a library snippet, not
2434 ;; a user snippet) OR
2436 ;; 2) yas/editing-template comes from a file that we cannot write to...
2438 (when (or (not (yas/template-file yas/editing-template))
2439 (not (file-writable-p (yas/template-file yas/editing-template)))
2440 (and (listp yas/snippet-dirs)
2441 (second yas/snippet-dirs)
2442 (not (string-match (expand-file-name (first yas/snippet-dirs))
2443 (yas/template-file yas/editing-template)))))
2445 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2446 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2448 (yas/make-directory-maybe option))))
2450 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2451 (file-name-nondirectory (yas/template-file yas/editing-template)))
2452 (yas/template-name yas/editing-template))))
2453 (write-file (concat chosen "/"
2454 (read-from-minibuffer (format "File name to create in %s? " chosen)
2455 default-file-name)))
2456 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2459 (message "[yas] Snippet \"%s\" loaded for %s."
2460 (yas/template-name yas/editing-template)
2461 (yas/table-name (yas/template-table yas/editing-template))))
2464 (defun yas/tryout-snippet (&optional debug)
2465 "Test current buffers's snippet template in other buffer."
2467 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2468 (parsed (yas/parse-template))
2469 (test-mode (or (and (car major-mode-and-parent)
2470 (fboundp (car major-mode-and-parent))
2471 (car major-mode-and-parent))
2472 (first yas/guessed-modes)
2473 (intern (read-from-minibuffer "[yas] Please input a mode: "))))
2474 (yas/current-template
2477 (yas/populate-template (yas/make-blank-template)
2478 :table nil ;; no tables for ephemeral snippets
2480 :content (second parsed)
2481 :name (third parsed)
2482 :expand-env (sixth parsed)))))
2483 (cond (yas/current-template
2484 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2485 (kill-buffer (get-buffer-create buffer-name))
2486 (switch-to-buffer (get-buffer-create buffer-name))
2487 (setq buffer-undo-list nil)
2488 (condition-case nil (funcall test-mode) (error nil))
2489 (setq buffer-read-only nil)
2490 (yas/expand-snippet (yas/template-content yas/current-template)
2493 (yas/template-expand-env yas/current-template))
2495 (require 'yasnippet-debug nil t))
2496 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2498 (message "[yas] Cannot test snippet for unknown major mode")))))
2500 (defun yas/template-fine-group (template)
2501 (car (last (or (yas/template-group template)
2502 (yas/template-perm-group template)))))
2504 (defun yas/describe-tables (&optional choose)
2505 "Display snippets for each table."
2507 (let* ((by-name-hash (and choose
2508 (y-or-n-p "Show by namehash? ")))
2509 (buffer (get-buffer-create "*YASnippet tables*"))
2510 (active-tables (yas/get-snippet-tables))
2511 (remain-tables (let ((all))
2512 (maphash #'(lambda (k v)
2513 (unless (find v active-tables)
2517 (table-lists (list active-tables remain-tables))
2518 (original-buffer (current-buffer))
2520 (yas/condition-cache-timestamp (current-time)))
2521 (with-current-buffer buffer
2522 (setq buffer-read-only nil)
2524 (cond ((not by-name-hash)
2525 (insert "YASnippet tables: \n")
2526 (while (and table-lists
2528 (dolist (table (car table-lists))
2529 (yas/describe-pretty-table table original-buffer))
2530 (setq table-lists (cdr table-lists))
2532 (yas/create-snippet-xrefs)
2533 (display-buffer buffer)
2534 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2535 (yas/create-snippet-xrefs)
2539 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2540 (dolist (table (append active-tables remain-tables))
2541 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2543 (maphash #'(lambda (k v)
2545 (yas/table-hash table))
2547 (insert (format " key %s maps snippets: %s\n" key
2549 (maphash #'(lambda (k v)
2551 (gethash key (yas/table-hash table)))
2554 (setq buffer-read-only t))
2555 (display-buffer buffer)))
2557 (defun yas/describe-pretty-table (table &optional original-buffer)
2558 (insert (format "\nSnippet table `%s'"
2559 (yas/table-name table)))
2560 (if (yas/table-parents table)
2561 (insert (format " parents: %s\n"
2562 (mapcar #'yas/table-name
2563 (yas/table-parents table))))
2565 (insert (make-string 100 ?-) "\n")
2566 (insert "group state name key binding\n")
2567 (let ((groups-alist (list))
2569 (maphash #'(lambda (k v)
2570 (setq group (or (yas/template-fine-group v)
2572 (when (yas/template-name v)
2574 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2575 (yas/table-uuidhash table))
2576 (dolist (group-and-templates groups-alist)
2577 (when (rest group-and-templates)
2578 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2579 (insert (make-string 100 ?-) "\n")
2580 (dolist (p (cdr group-and-templates))
2581 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2585 (setq group (make-string (length group) ? ))))
2586 (condition-string (let ((condition (yas/template-condition p)))
2589 (with-current-buffer original-buffer
2590 (if (yas/eval-condition condition)
2595 (insert condition-string " ")
2597 (if (string-match "\\.\\.\\.$" name)
2601 (insert (truncate-string-to-width (or (yas/template-key p) "")
2603 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2611 ;;; User convenience functions, for using in snippet definitions
2613 (defvar yas/modified-p nil
2614 "Non-nil if field has been modified by user or transformation.")
2616 (defvar yas/moving-away-p nil
2617 "Non-nil if user is about to exit field.")
2619 (defvar yas/text nil
2620 "Contains current field text.")
2622 (defun yas/substr (str pattern &optional subexp)
2623 "Search PATTERN in STR and return SUBEXPth match.
2625 If found, the content of subexp group SUBEXP (default 0) is
2626 returned, or else the original STR will be returned."
2627 (let ((grp (or subexp 0)))
2629 (if (string-match pattern str)
2630 (match-string-no-properties grp str)
2633 (defun yas/choose-value (possibilities)
2634 "Prompt for a string in the list POSSIBILITIES and return it."
2635 (unless (or yas/moving-away-p
2637 (some #'(lambda (fn)
2638 (funcall fn "Choose: " possibilities))
2639 yas/prompt-functions)))
2641 (defun yas/key-to-value (alist)
2642 "Prompt for a string in the list POSSIBILITIES and return it."
2643 (unless (or yas/moving-away-p
2645 (let ((key (read-key-sequence "")))
2647 (or (cdr (find key alist :key #'car :test #'string=))
2650 (defun yas/throw (text)
2651 "Throw a yas/exception with TEXT as the reason."
2652 (throw 'yas/exception (cons 'yas/exception text)))
2654 (defun yas/verify-value (possibilities)
2655 "Verify that the current field value is in POSSIBILITIES
2657 Otherwise throw exception."
2658 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2659 (yas/throw (format "[yas] Field only allows %s" possibilities))))
2661 (defun yas/field-value (number)
2662 "Get the string for field with NUMBER.
2664 Use this in primary and mirror transformations to tget."
2665 (let* ((snippet (car (yas/snippets-at-point)))
2667 (yas/snippet-find-field snippet number))))
2669 (yas/field-text-for-display field))))
2672 "Return `yas/text' if that exists and is non-empty, else nil."
2674 (not (string= "" yas/text)))
2677 ;; (defun yas/selected-text ()
2678 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2679 ;; (if (and yas/selected-text
2680 ;; (not (string= "" yas/selected-text)))
2681 ;; yas/selected-text))
2683 (defun yas/get-field-once (number &optional transform-fn)
2684 (unless yas/modified-p
2686 (funcall transform-fn (yas/field-value number))
2687 (yas/field-value number))))
2689 (defun yas/default-from-field (number)
2690 (unless yas/modified-p
2691 (yas/field-value number)))
2693 (defun yas/inside-string ()
2694 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2696 (defun yas/unimplemented (&optional missing-feature)
2697 (if yas/current-template
2698 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2701 (yas/visit-snippet-file-1 yas/current-template))
2702 (message "No implementation. Missing %s" (or missing-feature "something"))))
2705 ;;; Snippet expansion and field management
2707 (defvar yas/active-field-overlay nil
2708 "Overlays the currently active field.")
2710 (defvar yas/field-protection-overlays nil
2711 "Two overlays protect the current active field ")
2713 (defconst yas/prefix nil
2714 "A prefix argument for expansion direct from keybindings")
2716 (defvar yas/selected-text nil
2717 "The selected region deleted on the last snippet expansion.")
2719 (defvar yas/start-column nil
2720 "The column where the snippet expansion started.")
2722 (make-variable-buffer-local 'yas/active-field-overlay)
2723 (make-variable-buffer-local 'yas/field-protection-overlays)
2724 (put 'yas/active-field-overlay 'permanent-local t)
2725 (put 'yas/field-protection-overlays 'permanent-local t)
2727 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2733 (id (yas/snippet-next-id) :read-only t)
2734 (control-overlay nil)
2736 ;; stacked expansion: the `previous-active-field' slot saves the
2737 ;; active field where the child expansion took place
2738 previous-active-field
2741 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2751 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2758 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2762 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2763 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2765 If there is no transform for ht field, return nil.
2767 If there is a transform but it returns nil, return the empty
2768 string iff EMPTY-ON-NIL-P is true."
2769 (let* ((yas/text (yas/field-text-for-display field))
2771 (yas/modified-p (yas/field-modified-p field))
2772 (yas/moving-away-p nil)
2773 (transform (if (yas/mirror-p field-or-mirror)
2774 (yas/mirror-transform field-or-mirror)
2775 (yas/field-transform field-or-mirror)))
2776 (start-point (if (yas/mirror-p field-or-mirror)
2777 (yas/mirror-start field-or-mirror)
2778 (yas/field-start field-or-mirror)))
2779 (transformed (and transform
2781 (goto-char start-point)
2782 (let ((ret (yas/eval-lisp transform)))
2783 (or ret (and empty-on-nil-p "")))))))
2786 (defsubst yas/replace-all (from to &optional text)
2787 "Replace all occurance from FROM to TO.
2789 With optional string TEXT do it in that string."
2791 (replace-regexp-in-string (regexp-quote from) to text t t)
2792 (goto-char (point-min))
2793 (while (search-forward from nil t)
2794 (replace-match to t t text))))
2796 (defun yas/snippet-find-field (snippet number)
2797 (find-if #'(lambda (field)
2798 (eq number (yas/field-number field)))
2799 (yas/snippet-fields snippet)))
2801 (defun yas/snippet-sort-fields (snippet)
2802 "Sort the fields of SNIPPET in navigation order."
2803 (setf (yas/snippet-fields snippet)
2804 (sort (yas/snippet-fields snippet)
2805 #'yas/snippet-field-compare)))
2807 (defun yas/snippet-field-compare (field1 field2)
2808 "Compare two fields. The field with a number is sorted first.
2809 If they both have a number, compare through the number. If neither
2810 have, compare through the field's start point"
2811 (let ((n1 (yas/field-number field1))
2812 (n2 (yas/field-number field2)))
2815 (or (zerop n2) (and (not (zerop n1))
2820 (< (yas/field-start field1)
2821 (yas/field-start field2))))))
2823 (defun yas/field-probably-deleted-p (snippet field)
2824 "Guess if SNIPPET's FIELD should be skipped."
2825 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2826 (or (yas/field-parent-field field)
2827 (and (eq field (car (last (yas/snippet-fields snippet))))
2828 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2829 ;; the field numbered 0, just before the exit marker, should
2831 (not (zerop (yas/field-number field)))))
2833 (defun yas/snippets-at-point (&optional all-snippets)
2834 "Return a sorted list of snippets at point, most recently
2837 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2838 (overlay-get ov 'yas/snippet))
2840 (overlays-in (point-min) (point-max))
2841 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2843 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2845 (defun yas/next-field-or-maybe-expand ()
2846 "Try to expand a snippet at a key before point, otherwise
2847 delegate to `yas/next-field'."
2849 (if yas/triggers-in-field
2850 (let ((yas/fallback-behavior 'return-nil)
2851 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2853 (unless (yas/expand-from-trigger-key active-field)
2857 (defun yas/next-field (&optional arg)
2858 "Navigate to next field. If there's none, exit the snippet."
2862 (snippet (first (yas/snippets-at-point)))
2863 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2864 (live-fields (remove-if #'(lambda (field)
2865 (and (not (eq field active-field))
2866 (yas/field-probably-deleted-p snippet field)))
2867 (yas/snippet-fields snippet)))
2868 (active-field-pos (position active-field live-fields))
2869 (target-pos (and active-field-pos (+ arg active-field-pos)))
2870 (target-field (and target-pos (nth target-pos live-fields))))
2871 ;; First check if we're moving out of a field with a transform
2873 (when (and active-field
2874 (yas/field-transform active-field))
2875 (let* ((yas/moving-away-p t)
2876 (yas/text (yas/field-text-for-display active-field))
2878 (yas/modified-p (yas/field-modified-p active-field)))
2879 ;; primary field transform: exit call to field-transform
2880 (yas/eval-lisp (yas/field-transform active-field))))
2881 ;; Now actually move...
2882 (cond ((and target-pos (>= target-pos (length live-fields)))
2883 (yas/exit-snippet snippet))
2885 (yas/move-to-field snippet target-field))
2889 (defun yas/place-overlays (snippet field)
2890 "Correctly place overlays for SNIPPET's FIELD"
2891 (yas/make-move-field-protection-overlays snippet field)
2892 (yas/make-move-active-field-overlay snippet field))
2894 (defun yas/move-to-field (snippet field)
2895 "Update SNIPPET to move to field FIELD.
2897 Also create some protection overlays"
2898 (goto-char (yas/field-start field))
2899 (yas/place-overlays snippet field)
2900 (overlay-put yas/active-field-overlay 'yas/field field)
2901 (let ((number (yas/field-number field)))
2902 ;; check for the special ${0: ...} field
2903 (if (and number (zerop number))
2905 (set-mark (yas/field-end field))
2906 (setf (yas/snippet-force-exit snippet)
2907 (or (yas/field-transform field)
2909 ;; make this field active
2910 (setf (yas/snippet-active-field snippet) field)
2911 ;; primary field transform: first call to snippet transform
2912 (unless (yas/field-modified-p field)
2913 (if (yas/field-update-display field snippet)
2914 (yas/update-mirrors snippet)
2915 (setf (yas/field-modified-p field) nil))))))
2917 (defun yas/prev-field ()
2918 "Navigate to prev field. If there's none, exit the snippet."
2920 (yas/next-field -1))
2922 (defun yas/abort-snippet (&optional snippet)
2924 (let ((snippet (or snippet
2925 (car (yas/snippets-at-point)))))
2927 (setf (yas/snippet-force-exit snippet) t))))
2929 (defun yas/exit-snippet (snippet)
2930 "Goto exit-marker of SNIPPET."
2931 (interactive (list (first (yas/snippets-at-point))))
2933 (setf (yas/snippet-force-exit snippet) t)
2934 (goto-char (if (yas/snippet-exit snippet)
2935 (yas/exit-marker (yas/snippet-exit snippet))
2936 (overlay-end (yas/snippet-control-overlay snippet))))))
2938 (defun yas/exit-all-snippets ()
2939 "Exit all snippets."
2941 (mapc #'(lambda (snippet)
2942 (yas/exit-snippet snippet)
2943 (yas/check-commit-snippet))
2944 (yas/snippets-at-point)))
2947 ;;; Some low level snippet-routines
2949 (defmacro yas/inhibit-overlay-hooks (&rest body)
2950 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
2951 (declare (indent 0))
2952 `(let ((yas/inhibit-overlay-hooks t))
2955 (defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
2956 (defvar yas/snippet-end nil "End position of the last snippet commited.")
2958 (defun yas/commit-snippet (snippet)
2959 "Commit SNIPPET, but leave point as it is. This renders the
2960 snippet as ordinary text."
2962 (let ((control-overlay (yas/snippet-control-overlay snippet)))
2964 ;; Save the end of the moribund snippet in case we need to revive it
2965 ;; its original expansion.
2967 (when (and control-overlay
2968 (overlay-buffer control-overlay))
2969 (setq yas/snippet-beg (overlay-start control-overlay))
2970 (setq yas/snippet-end (overlay-end control-overlay))
2971 (delete-overlay control-overlay))
2973 (yas/inhibit-overlay-hooks
2974 (when yas/active-field-overlay
2975 (delete-overlay yas/active-field-overlay))
2976 (when yas/field-protection-overlays
2977 (mapc #'delete-overlay yas/field-protection-overlays)))
2979 ;; stacked expansion: if the original expansion took place from a
2980 ;; field, make sure we advance it here at least to
2981 ;; `yas/snippet-end'...
2983 (let ((previous-field (yas/snippet-previous-active-field snippet)))
2984 (when (and yas/snippet-end previous-field)
2985 (yas/advance-end-maybe previous-field yas/snippet-end)))
2987 ;; Convert all markers to points,
2989 (yas/markers-to-points snippet)
2991 ;; Take care of snippet revival
2993 (if yas/snippet-revival
2994 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
2996 ;; Dismember the snippet... this is useful if we get called
2997 ;; again from `yas/take-care-of-redo'....
2998 (setf (yas/snippet-fields snippet) nil)))
3000 (message "[yas] Snippet %s exited." (yas/snippet-id snippet)))
3002 (defun yas/safely-run-hooks (hook-var)
3003 (condition-case error
3004 (run-hooks hook-var)
3006 (message "[yas] %s error: %s" hook-var (error-message-string error)))))
3009 (defun yas/check-commit-snippet ()
3010 "Checks if point exited the currently active field of the
3011 snippet, if so cleans up the whole snippet up."
3012 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3013 (snippets-left snippets)
3014 (snippet-exit-transform))
3015 (dolist (snippet snippets)
3016 (let ((active-field (yas/snippet-active-field snippet)))
3017 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3018 (cond ((or snippet-exit-transform
3019 (not (and active-field (yas/field-contains-point-p active-field))))
3020 (setq snippets-left (delete snippet snippets-left))
3021 (setf (yas/snippet-force-exit snippet) nil)
3022 (yas/commit-snippet snippet))
3024 (or (not yas/active-field-overlay)
3025 (not (overlay-buffer yas/active-field-overlay))))
3027 ;; stacked expansion: this case is mainly for recent
3028 ;; snippet exits that place us back int the field of
3032 (yas/move-to-field snippet active-field)
3033 (yas/update-mirrors snippet)))
3036 (unless (or (null snippets) snippets-left)
3037 (if snippet-exit-transform
3038 (yas/eval-lisp-no-saves snippet-exit-transform))
3039 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3041 ;; Apropos markers-to-points:
3043 ;; This was found useful for performance reasons, so that an
3044 ;; excessive number of live markers aren't kept around in the
3045 ;; `buffer-undo-list'. However, in `markers-to-points', the
3046 ;; set-to-nil markers can't simply be discarded and replaced with
3047 ;; fresh ones in `points-to-markers'. The original marker that was
3048 ;; just set to nil has to be reused.
3050 ;; This shouldn't bring horrible problems with undo/redo, but it
3053 (defun yas/markers-to-points (snippet)
3054 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3055 where POINT is the original position of the marker and MARKER is
3056 the original marker object with the position set to nil."
3057 (dolist (field (yas/snippet-fields snippet))
3058 (let ((start (marker-position (yas/field-start field)))
3059 (end (marker-position (yas/field-end field))))
3060 (set-marker (yas/field-start field) nil)
3061 (set-marker (yas/field-end field) nil)
3062 (setf (yas/field-start field) (cons start (yas/field-start field)))
3063 (setf (yas/field-end field) (cons end (yas/field-end field))))
3064 (dolist (mirror (yas/field-mirrors field))
3065 (let ((start (marker-position (yas/mirror-start mirror)))
3066 (end (marker-position (yas/mirror-end mirror))))
3067 (set-marker (yas/mirror-start mirror) nil)
3068 (set-marker (yas/mirror-end mirror) nil)
3069 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3070 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3071 (let ((snippet-exit (yas/snippet-exit snippet)))
3073 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3074 (set-marker (yas/exit-marker snippet-exit) nil)
3075 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3077 (defun yas/points-to-markers (snippet)
3078 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3079 is done by setting MARKER to POINT with `set-marker'."
3080 (dolist (field (yas/snippet-fields snippet))
3081 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3082 (car (yas/field-start field))))
3083 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3084 (car (yas/field-end field))))
3085 (dolist (mirror (yas/field-mirrors field))
3086 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3087 (car (yas/mirror-start mirror))))
3088 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3089 (car (yas/mirror-end mirror))))))
3090 (let ((snippet-exit (yas/snippet-exit snippet)))
3092 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3093 (car (yas/exit-marker snippet-exit)))))))
3095 (defun yas/field-contains-point-p (field &optional point)
3096 (let ((point (or point
3098 (and (>= point (yas/field-start field))
3099 (<= point (yas/field-end field)))))
3101 (defun yas/field-text-for-display (field)
3102 "Return the propertized display text for field FIELD. "
3103 (buffer-substring (yas/field-start field) (yas/field-end field)))
3105 (defun yas/undo-in-progress ()
3106 "True if some kind of undo is in progress"
3107 (or undo-in-progress
3108 (eq this-command 'undo)
3109 (eq this-command 'redo)))
3111 (defun yas/make-control-overlay (snippet start end)
3112 "Creates the control overlay that surrounds the snippet and
3114 (let ((overlay (make-overlay start
3119 (overlay-put overlay 'keymap yas/keymap)
3120 (overlay-put overlay 'priority 100)
3121 (overlay-put overlay 'yas/snippet snippet)
3124 (defun yas/skip-and-clear-or-delete-char (&optional field)
3125 "Clears unmodified field if at field start, skips to next tab.
3127 Otherwise deletes a character normally by calling `delete-char'."
3129 (let ((field (or field
3130 (and yas/active-field-overlay
3131 (overlay-buffer yas/active-field-overlay)
3132 (overlay-get yas/active-field-overlay 'yas/field)))))
3134 (not (yas/field-modified-p field))
3135 (eq (point) (marker-position (yas/field-start field))))
3136 (yas/skip-and-clear field)
3139 (call-interactively 'delete-char)))))
3141 (defun yas/skip-and-clear (field)
3142 "Deletes the region of FIELD and sets it modified state to t"
3143 ;; Just before skipping-and-clearing the field, mark its children
3144 ;; fields as modified, too. If the childen have mirrors-in-fields
3145 ;; this prevents them from updating erroneously (we're skipping and
3148 (yas/mark-this-and-children-modified field)
3149 (delete-region (yas/field-start field) (yas/field-end field)))
3151 (defun yas/mark-this-and-children-modified (field)
3152 (setf (yas/field-modified-p field) t)
3153 (let ((fom (yas/field-next field)))
3155 (yas/fom-parent-field fom))
3156 (when (and (eq (yas/fom-parent-field fom) field)
3158 (yas/mark-this-and-children-modified fom))
3159 (setq fom (yas/fom-next fom)))))
3161 (defun yas/make-move-active-field-overlay (snippet field)
3162 "Place the active field overlay in SNIPPET's FIELD.
3164 Move the overlay, or create it if it does not exit."
3165 (if (and yas/active-field-overlay
3166 (overlay-buffer yas/active-field-overlay))
3167 (move-overlay yas/active-field-overlay
3168 (yas/field-start field)
3169 (yas/field-end field))
3170 (setq yas/active-field-overlay
3171 (make-overlay (yas/field-start field)
3172 (yas/field-end field)
3174 (overlay-put yas/active-field-overlay 'priority 100)
3175 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3176 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3177 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3178 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3179 '(yas/on-field-overlay-modification))
3180 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3181 '(yas/on-field-overlay-modification))))
3183 (defvar yas/inhibit-overlay-hooks nil
3184 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3186 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3187 "Clears the field and updates mirrors, conditionally.
3189 Only clears the field if it hasn't been modified and it point it
3190 at field start. This hook doesn't do anything if an undo is in
3192 (unless (or yas/inhibit-overlay-hooks
3193 (yas/undo-in-progress))
3194 (let* ((field (overlay-get overlay 'yas/field))
3195 (number (and field (yas/field-number field)))
3196 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3198 (yas/advance-end-maybe field (overlay-end overlay))
3200 (yas/field-update-display field snippet))
3201 (yas/update-mirrors snippet))
3203 (when (and (not after?)
3204 (not (yas/field-modified-p field))
3205 (eq (point) (if (markerp (yas/field-start field))
3206 (marker-position (yas/field-start field))
3207 (yas/field-start field))))
3208 (yas/skip-and-clear field))
3209 (setf (yas/field-modified-p field) t))))))
3211 ;;; Apropos protection overlays:
3213 ;; These exist for nasty users who will try to delete parts of the
3214 ;; snippet outside the active field. Actual protection happens in
3215 ;; `yas/on-protection-overlay-modification'.
3217 ;; Currently this signals an error which inhibits the command. For
3218 ;; commands that move point (like `kill-line'), point is restored in
3219 ;; the `yas/post-command-handler' using a global
3220 ;; `yas/protection-violation' variable.
3222 ;; Alternatively, I've experimented with an implementation that
3223 ;; commits the snippet before actually calling `this-command'
3224 ;; interactively, and then signals an eror, which is ignored. but
3225 ;; blocks all other million modification hooks. This presented some
3226 ;; problems with stacked expansion.
3229 (defun yas/make-move-field-protection-overlays (snippet field)
3230 "Place protection overlays surrounding SNIPPET's FIELD.
3232 Move the overlays, or create them if they do not exit."
3233 (let ((start (yas/field-start field))
3234 (end (yas/field-end field)))
3235 ;; First check if the (1+ end) is contained in the buffer,
3236 ;; otherwise we'll have to do a bit of cheating and silently
3237 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3238 ;; when using stacked expansion
3240 (when (< (buffer-size) end)
3242 (yas/inhibit-overlay-hooks
3243 (goto-char (point-max))
3245 ;; go on to normal overlay creation/moving
3247 (cond ((and yas/field-protection-overlays
3248 (every #'overlay-buffer yas/field-protection-overlays))
3249 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3250 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3252 (setq yas/field-protection-overlays
3253 (list (make-overlay (1- start) start nil t nil)
3254 (make-overlay end (1+ end) nil t nil)))
3255 (dolist (ov yas/field-protection-overlays)
3256 (overlay-put ov 'face 'yas/field-debug-face)
3257 (overlay-put ov 'yas/snippet snippet)
3258 ;; (overlay-put ov 'evaporate t)
3259 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3261 (defvar yas/protection-violation nil
3262 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3264 Functions in the `post-command-hook', for example
3265 `yas/post-command-handler' can check it and reset its value to
3266 nil. The variables value is the point where the violation
3269 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3270 "Signals a snippet violation, then issues error.
3272 The error should be ignored in `debug-ignored-errors'"
3273 (unless yas/inhibit-overlay-hooks
3274 (cond ((not (or after?
3275 (yas/undo-in-progress)))
3276 (setq yas/protection-violation (point))
3277 (error "Exit the snippet first!")))))
3279 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3282 ;;; Apropos stacked expansion:
3284 ;; the parent snippet does not run its fields modification hooks
3285 ;; (`yas/on-field-overlay-modification' and
3286 ;; `yas/on-protection-overlay-modification') while the child snippet
3287 ;; is active. This means, among other things, that the mirrors of the
3288 ;; parent snippet are not updated, this only happening when one exits
3289 ;; the child snippet.
3291 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3292 ;; bits of code in `yas/expand-snippet' and
3293 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3296 ;; This was thought to be safer in in an undo/redo perpective, but
3297 ;; maybe the correct implementation is to make the globals
3298 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3299 ;; snippet-local and be active even while the child snippet is
3300 ;; running. This would mean a lot of overlay modification hooks
3301 ;; running, but if managed correctly (including overlay priorities)
3302 ;; they should account for all situations...
3305 (defun yas/expand-snippet (content &optional start end expand-env)
3306 "Expand snippet CONTENT at current point.
3308 Text between START and END will be deleted before inserting
3309 template. EXPAND-ENV is are let-style variable to value bindings
3310 considered when expanding the snippet."
3311 (run-hooks 'yas/before-expand-snippet-hook)
3313 ;; If a region is active, set `yas/selected-text'
3314 (setq yas/selected-text
3315 (when (region-active-p)
3316 (prog1 (buffer-substring-no-properties (region-beginning)
3318 (unless start (setq start (region-beginning))
3319 (unless end (setq end (region-end)))))))
3325 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3326 (start (or start (point)))
3327 (end (or end (point)))
3329 (setq yas/indent-original-column (current-column))
3330 ;; Delete the region to delete, this *does* get undo-recorded.
3332 (when (and to-delete
3334 (delete-region start end))
3336 (cond ((listp content)
3337 ;; x) This is a snippet-command
3339 (yas/eval-lisp-no-saves content))
3341 ;; x) This is a snippet-snippet :-)
3343 ;; Narrow the region down to the content, shoosh the
3344 ;; `buffer-undo-list', and create the snippet, the new
3345 ;; snippet updates its mirrors once, so we are left with
3346 ;; some plain text. The undo action for deleting this
3347 ;; plain text will get recorded at the end.
3349 ;; stacked expansion: also shoosh the overlay modification hooks
3351 (narrow-to-region start start)
3352 (let ((buffer-undo-list t))
3353 ;; snippet creation might evaluate users elisp, which
3354 ;; might generate errors, so we have to be ready to catch
3355 ;; them mostly to make the undo information
3357 (setq yas/start-column (save-restriction (widen) (current-column)))
3358 (yas/inhibit-overlay-hooks
3361 (eval `(let* ,expand-env
3363 (yas/snippet-create (point-min) (point-max))))
3365 (yas/snippet-create (point-min) (point-max)))))))
3367 ;; stacked-expansion: This checks for stacked expansion, save the
3368 ;; `yas/previous-active-field' and advance its boudary.
3370 (let ((existing-field (and yas/active-field-overlay
3371 (overlay-buffer yas/active-field-overlay)
3372 (overlay-get yas/active-field-overlay 'yas/field))))
3373 (when existing-field
3374 (setf (yas/snippet-previous-active-field snippet) existing-field)
3375 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3377 ;; Exit the snippet immediately if no fields
3379 (unless (yas/snippet-fields snippet)
3380 (yas/exit-snippet snippet))
3382 ;; Push two undo actions: the deletion of the inserted contents of
3383 ;; the new snippet (without the "key") followed by an apply of
3384 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3386 ;; A small exception, if `yas/also-auto-indent-first-line'
3387 ;; is t and `yas/indent' decides to indent the line to a
3388 ;; point before the actual expansion point, undo would be
3389 ;; messed up. We call the early point "newstart"". case,
3390 ;; and attempt to fix undo.
3392 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3393 (end (overlay-end (yas/snippet-control-overlay snippet))))
3394 (when (< newstart start)
3395 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3396 (push (cons newstart end) buffer-undo-list)
3397 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3399 ;; Now, schedule a move to the first field
3401 (let ((first-field (car (yas/snippet-fields snippet))))
3403 (sit-for 0) ;; fix issue 125
3404 (yas/move-to-field snippet first-field)))
3405 (message "[yas] snippet expanded.")
3408 (defun yas/take-care-of-redo (beg end snippet)
3409 "Commits SNIPPET, which in turn pushes an undo action for
3412 Meant to exit in the `buffer-undo-list'."
3413 ;; slightly optimize: this action is only needed for snippets with
3414 ;; at least one field
3415 (when (yas/snippet-fields snippet)
3416 (yas/commit-snippet snippet)))
3418 (defun yas/snippet-revive (beg end snippet)
3419 "Revives the SNIPPET and creates a control overlay from BEG to
3422 BEG and END are, we hope, the original snippets boudaries. All
3423 the markers/points exiting existing inside SNIPPET should point
3424 to their correct locations *at the time the snippet is revived*.
3426 After revival, push the `yas/take-care-of-redo' in the
3428 ;; Reconvert all the points to markers
3430 (yas/points-to-markers snippet)
3431 ;; When at least one editable field existed in the zombie snippet,
3432 ;; try to revive the whole thing...
3434 (let ((target-field (or (yas/snippet-active-field snippet)
3435 (car (yas/snippet-fields snippet)))))
3437 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3438 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3440 (yas/move-to-field snippet target-field)
3442 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3443 buffer-undo-list))))
3445 (defun yas/snippet-create (begin end)
3446 "Creates a snippet from an template inserted between BEGIN and END.
3448 Returns the newly created snippet."
3449 (let ((snippet (yas/make-snippet)))
3451 (yas/snippet-parse-create snippet)
3453 ;; Sort and link each field
3454 (yas/snippet-sort-fields snippet)
3456 ;; Create keymap overlay for snippet
3457 (setf (yas/snippet-control-overlay snippet)
3458 (yas/make-control-overlay snippet (point-min) (point-max)))
3461 (goto-char (point-max))
3466 ;;; Apropos adjacencies and "fom's":
3468 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3469 ;; recently expanded snippet, we might actually have many fields,
3470 ;; mirrors (and the snippet exit) in the very same position in the
3471 ;; buffer. Therefore we need to single-link the
3472 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3473 ;; their original positions in the buffer.
3475 ;; Then we have operation `yas/advance-end-maybe' and
3476 ;; `yas/advance-start-maybe', which conditionally push the starts and
3477 ;; ends of these foms down the chain.
3479 ;; This allows for like the printf with the magic ",":
3481 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3482 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3484 (defun yas/fom-start (fom)
3485 (cond ((yas/field-p fom)
3486 (yas/field-start fom))
3488 (yas/mirror-start fom))
3490 (yas/exit-marker fom))))
3492 (defun yas/fom-end (fom)
3493 (cond ((yas/field-p fom)
3494 (yas/field-end fom))
3496 (yas/mirror-end fom))
3498 (yas/exit-marker fom))))
3500 (defun yas/fom-next (fom)
3501 (cond ((yas/field-p fom)
3502 (yas/field-next fom))
3504 (yas/mirror-next fom))
3506 (yas/exit-next fom))))
3508 (defun yas/fom-parent-field (fom)
3509 (cond ((yas/field-p fom)
3510 (yas/field-parent-field fom))
3512 (yas/mirror-parent-field fom))
3516 (defun yas/calculate-adjacencies (snippet)
3517 "Calculate adjacencies for fields or mirrors of SNIPPET.
3519 This is according to their relative positions in the buffer, and
3520 has to be called before the $-constructs are deleted."
3521 (flet ((yas/fom-set-next-fom (fom nextfom)
3522 (cond ((yas/field-p fom)
3523 (setf (yas/field-next fom) nextfom))
3525 (setf (yas/mirror-next fom) nextfom))
3527 (setf (yas/exit-next fom) nextfom))))
3528 (yas/compare-fom-begs (fom1 fom2)
3529 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3531 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3532 (yas/link-foms (fom1 fom2)
3533 (yas/fom-set-next-fom fom1 fom2)))
3534 ;; make some yas/field, yas/mirror and yas/exit soup
3536 (when (yas/snippet-exit snippet)
3537 (push (yas/snippet-exit snippet) soup))
3538 (dolist (field (yas/snippet-fields snippet))
3540 (dolist (mirror (yas/field-mirrors field))
3541 (push mirror soup)))
3544 #'yas/compare-fom-begs))
3546 (reduce #'yas/link-foms soup)))))
3548 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3549 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3551 Use the tighest containing field if more than one field contains
3552 the mirror. Intended to be called *before* the dollar-regions are
3554 (let ((min (point-min))
3556 (dolist (field (yas/snippet-fields snippet))
3557 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3558 (<= (yas/mirror-end mirror) (yas/field-end field))
3559 (< min (yas/field-start field))
3560 (< (yas/field-end field) max))
3561 (setq min (yas/field-start field)
3562 max (yas/field-end field))
3563 (setf (yas/mirror-parent-field mirror) field)))))
3565 (defun yas/advance-end-maybe (fom newend)
3566 "Maybe advance FOM's end to NEWEND if it needs it.
3570 * call `yas/advance-start-maybe' on FOM's next fom.
3572 * in case FOM is field call `yas/advance-end-maybe' on its parent
3575 Also, if FOM is an exit-marker, always call
3576 `yas/advance-start-maybe' on its next fom. This is beacuse
3577 exit-marker have identical start and end markers.
3580 (cond ((and fom (< (yas/fom-end fom) newend))
3581 (set-marker (yas/fom-end fom) newend)
3582 (yas/advance-start-maybe (yas/fom-next fom) newend)
3583 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3585 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3587 (defun yas/advance-start-maybe (fom newstart)
3588 "Maybe advance FOM's start to NEWSTART if it needs it.
3590 If it does, also call `yas/advance-end-maybe' on FOM."
3591 (when (and fom (< (yas/fom-start fom) newstart))
3592 (set-marker (yas/fom-start fom) newstart)
3593 (yas/advance-end-maybe fom newstart)))
3595 (defun yas/advance-end-of-parents-maybe (field newend)
3596 "Like `yas/advance-end-maybe' but for parent fields.
3598 Only works for fields and doesn't care about the start of the
3599 next FOM. Works its way up recursively for parents of parents."
3601 (< (yas/field-end field) newend))
3602 (set-marker (yas/field-end field) newend)
3603 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3605 (defvar yas/dollar-regions nil
3606 "When expanding the snippet the \"parse-create\" functions add
3607 cons cells to this var")
3609 (defun yas/snippet-parse-create (snippet)
3610 "Parse a recently inserted snippet template, creating all
3611 necessary fields, mirrors and exit points.
3613 Meant to be called in a narrowed buffer, does various passes"
3614 (let ((parse-start (point)))
3615 ;; Reset the yas/dollar-regions
3617 (setq yas/dollar-regions nil)
3618 ;; protect escaped quote, backquotes and backslashes
3620 (yas/protect-escapes nil `(?\\ ?` ?'))
3621 ;; replace all backquoted expressions
3623 (goto-char parse-start)
3624 (yas/replace-backquotes)
3625 ;; protect escapes again since previous steps might have generated
3626 ;; more characters needing escaping
3628 (goto-char parse-start)
3629 (yas/protect-escapes)
3630 ;; parse fields with {}
3632 (goto-char parse-start)
3633 (yas/field-parse-create snippet)
3634 ;; parse simple mirrors and fields
3636 (goto-char parse-start)
3637 (yas/simple-mirror-parse-create snippet)
3638 ;; parse mirror transforms
3640 (goto-char parse-start)
3641 (yas/transform-mirror-parse-create snippet)
3642 ;; calculate adjacencies of fields and mirrors
3644 (yas/calculate-adjacencies snippet)
3645 ;; Delete $-constructs
3647 (yas/delete-regions yas/dollar-regions)
3650 (goto-char parse-start)
3651 (yas/restore-escapes)
3652 ;; update mirrors for the first time
3654 (yas/update-mirrors snippet)
3655 ;; indent the best we can
3657 (goto-char parse-start)
3658 (yas/indent snippet)))
3660 (defun yas/indent-according-to-mode (snippet-markers)
3661 "Indent current line according to mode, preserving
3663 ;;; Apropos indenting problems....
3665 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3666 ;; is available. Some implementations of these functions delete text
3667 ;; before they insert. If there happens to be a marker just after
3668 ;; the text being deleted, the insertion actually happens after the
3669 ;; marker, which misplaces it.
3671 ;; This would also happen if we had used overlays with the
3672 ;; `front-advance' property set to nil.
3674 ;; This is why I have these `trouble-markers', they are the ones at
3675 ;; they are the ones at the first non-whitespace char at the line
3676 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3677 ;; we should be at the correct to restore them to. All other
3678 ;; non-trouble-markers have been *pushed* and don't need special
3681 (goto-char (yas/real-line-beginning))
3682 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3688 (indent-according-to-mode)
3689 (error (message "[yas] warning: `yas/indent-according-to-mode' having problems running %s" indent-line-function)
3691 (mapc #'(lambda (marker)
3692 (set-marker marker (point)))
3695 (defvar yas/indent-original-column nil)
3696 (defun yas/indent (snippet)
3697 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3698 ;; Look for those $>
3700 (while (re-search-forward "$>" nil t)
3701 (delete-region (match-beginning 0) (match-end 0))
3702 (when (not (eq yas/indent-line 'auto))
3703 (yas/indent-according-to-mode snippet-markers))))
3704 ;; Now do stuff for 'fixed and 'auto
3706 (cond ((eq yas/indent-line 'fixed)
3707 (while (and (zerop (forward-line))
3708 (zerop (current-column)))
3709 (indent-to-column yas/indent-original-column)))
3710 ((eq yas/indent-line 'auto)
3711 (let ((end (set-marker (make-marker) (point-max)))
3712 (indent-first-line-p yas/also-auto-indent-first-line))
3713 (while (and (zerop (if indent-first-line-p
3716 (setq indent-first-line-p nil))
3720 (yas/indent-according-to-mode snippet-markers))))
3724 (defun yas/collect-snippet-markers (snippet)
3725 "Make a list of all the markers used by SNIPPET."
3727 (dolist (field (yas/snippet-fields snippet))
3728 (push (yas/field-start field) markers)
3729 (push (yas/field-end field) markers)
3730 (dolist (mirror (yas/field-mirrors field))
3731 (push (yas/mirror-start mirror) markers)
3732 (push (yas/mirror-end mirror) markers)))
3733 (let ((snippet-exit (yas/snippet-exit snippet)))
3734 (when (and snippet-exit
3735 (marker-buffer (yas/exit-marker snippet-exit)))
3736 (push (yas/exit-marker snippet-exit) markers)))
3739 (defun yas/real-line-beginning ()
3740 (let ((c (char-after (line-beginning-position)))
3741 (n (line-beginning-position)))
3742 (while (or (eql c ?\ )
3745 (setq c (char-after n)))
3748 (defun yas/escape-string (escaped)
3749 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3751 (defun yas/protect-escapes (&optional text escaped)
3752 "Protect all escaped characters with their numeric ASCII value.
3754 With optional string TEXT do it in string instead of buffer."
3755 (let ((changed-text text)
3756 (text-provided-p text))
3757 (mapc #'(lambda (escaped)
3759 (yas/replace-all (concat "\\" (char-to-string escaped))
3760 (yas/escape-string escaped)
3761 (when text-provided-p changed-text))))
3762 (or escaped yas/escaped-characters))
3765 (defun yas/restore-escapes (&optional text escaped)
3766 "Restore all escaped characters from their numeric ASCII value.
3768 With optional string TEXT do it in string instead of the buffer."
3769 (let ((changed-text text)
3770 (text-provided-p text))
3771 (mapc #'(lambda (escaped)
3773 (yas/replace-all (yas/escape-string escaped)
3774 (char-to-string escaped)
3775 (when text-provided-p changed-text))))
3776 (or escaped yas/escaped-characters))
3779 (defun yas/replace-backquotes ()
3780 "Replace all the \"`(lisp-expression)`\"-style expression
3781 with their evaluated value"
3782 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3783 (let ((current-string (match-string 1)) transformed)
3784 (delete-region (match-beginning 0) (match-end 0))
3785 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3786 (goto-char (match-beginning 0))
3787 (when transformed (insert transformed)))))
3789 (defun yas/scan-sexps (from count)
3791 (with-syntax-table (standard-syntax-table)
3792 (scan-sexps from count))
3796 (defun yas/make-marker (pos)
3797 "Create a marker at POS with `nil' `marker-insertion-type'"
3798 (let ((marker (set-marker (make-marker) pos)))
3799 (set-marker-insertion-type marker nil)
3802 (defun yas/field-parse-create (snippet &optional parent-field)
3803 "Parse most field expressions, except for the simple one \"$n\".
3805 The following count as a field:
3807 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3809 * \"${n: text$(expression)}, the same with a lisp expression;
3810 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3812 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3814 When multiple expressions are found, only the last one counts."
3817 (while (re-search-forward yas/field-regexp nil t)
3818 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3819 (number (and (match-string-no-properties 1)
3820 (string-to-number (match-string-no-properties 1))))
3821 (brand-new-field (and real-match-end-0
3822 ;; break if on "$(" immediately
3823 ;; after the ":", this will be
3824 ;; caught as a mirror with
3826 (not (save-match-data
3827 (eq (string-match "$[ \t\n]*("
3828 (match-string-no-properties 2)) 0)))
3829 ;; allow ${0: some exit text}
3830 ;; (not (and number (zerop number)))
3831 (yas/make-field number
3832 (yas/make-marker (match-beginning 2))
3833 (yas/make-marker (1- real-match-end-0))
3835 (when brand-new-field
3836 (goto-char real-match-end-0)
3837 (push (cons (1- real-match-end-0) real-match-end-0)
3839 (push (cons (match-beginning 0) (match-beginning 2))
3841 (push brand-new-field (yas/snippet-fields snippet))
3844 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3845 (goto-char (point-min))
3846 (yas/field-parse-create snippet brand-new-field)))))))
3847 ;; if we entered from a parent field, now search for the
3848 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3849 ;; primary field transformations
3853 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3854 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3855 ;; commit the primary field transformation if:
3857 ;; 1. we don't find it in yas/dollar-regions (a subnested
3858 ;; field) might have already caught it.
3860 ;; 2. we really make sure we have either two '$' or some
3861 ;; text and a '$' after the colon ':'. This is a FIXME: work
3862 ;; my regular expressions and end these ugly hacks.
3864 (when (and real-match-end-1
3865 (not (member (cons (match-beginning 0)
3867 yas/dollar-regions))
3869 (char-before (1- (match-beginning 1))))))
3870 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3872 (setf (yas/field-transform parent-field)
3873 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3874 (push (cons (match-beginning 0) real-match-end-1)
3875 yas/dollar-regions)))))))
3877 (defun yas/transform-mirror-parse-create (snippet)
3878 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3879 (while (re-search-forward yas/transform-mirror-regexp nil t)
3880 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3881 (number (string-to-number (match-string-no-properties 1)))
3883 (not (zerop number))
3884 (yas/snippet-find-field snippet number)))
3886 (and real-match-end-0
3888 (yas/make-mirror (yas/make-marker (match-beginning 0))
3889 (yas/make-marker (match-beginning 0))
3891 (yas/restore-escapes
3892 (buffer-substring-no-properties (match-beginning 2)
3893 (1- real-match-end-0))))))))
3894 (when brand-new-mirror
3895 (push brand-new-mirror
3896 (yas/field-mirrors field))
3897 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3898 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3900 (defun yas/simple-mirror-parse-create (snippet)
3901 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3902 (while (re-search-forward yas/simple-mirror-regexp nil t)
3903 (let ((number (string-to-number (match-string-no-properties 1))))
3904 (cond ((zerop number)
3906 (setf (yas/snippet-exit snippet)
3907 (yas/make-exit (yas/make-marker (match-end 0))))
3909 (goto-char (match-beginning 0))
3910 (when yas/wrap-around-region
3911 (cond (yas/selected-text
3912 (insert yas/selected-text))
3913 ((and (eq yas/wrap-around-region 'cua)
3916 (insert (prog1 (get-register ?0)
3917 (set-register ?0 nil))))))
3918 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3919 yas/dollar-regions)))
3921 (let ((field (yas/snippet-find-field snippet number)))
3923 (let ((brand-new-mirror (yas/make-mirror
3924 (yas/make-marker (match-beginning 0))
3925 (yas/make-marker (match-beginning 0))
3927 (push brand-new-mirror
3928 (yas/field-mirrors field))
3929 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
3930 (push (yas/make-field number
3931 (yas/make-marker (match-beginning 0))
3932 (yas/make-marker (match-beginning 0))
3934 (yas/snippet-fields snippet))))
3935 (push (cons (match-beginning 0) (match-end 0))
3936 yas/dollar-regions))))))
3938 (defun yas/delete-regions (regions)
3939 "Sort disjuct REGIONS by start point, then delete from the back."
3940 (mapc #'(lambda (reg)
3941 (delete-region (car reg) (cdr reg)))
3944 (>= (car r1) (car r2))))))
3946 (defun yas/update-mirrors (snippet)
3947 "Updates all the mirrors of SNIPPET."
3949 (let* ((fields (copy-list (yas/snippet-fields snippet)))
3950 (field (car fields)))
3952 (dolist (mirror (yas/field-mirrors field))
3953 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
3954 ;; updatte this mirror
3956 (yas/mirror-update-display mirror field)
3957 ;; for mirrors-in-fields: schedule a possible
3958 ;; parent field for reupdting later on
3960 (when mirror-parent-field
3961 (add-to-list 'fields mirror-parent-field 'append #'eq))
3962 ;; `yas/place-overlays' is needed if the active field and
3963 ;; protected overlays have been changed because of insertions
3964 ;; in `yas/mirror-update-display'
3966 (when (eq field (yas/snippet-active-field snippet))
3967 (yas/place-overlays snippet field))))
3968 (setq fields (cdr fields))
3969 (setq field (car fields))))))
3971 (defun yas/mirror-update-display (mirror field)
3972 "Update MIRROR according to FIELD (and mirror transform)."
3974 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
3975 (reflection (and (not (and mirror-parent-field
3976 (yas/field-modified-p mirror-parent-field)))
3977 (or (yas/apply-transform mirror field 'empty-on-nil)
3978 (yas/field-text-for-display field)))))
3979 (when (and reflection
3980 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
3981 (yas/mirror-end mirror)))))
3982 (goto-char (yas/mirror-start mirror))
3983 (yas/inhibit-overlay-hooks
3984 (insert reflection))
3985 (if (> (yas/mirror-end mirror) (point))
3986 (delete-region (point) (yas/mirror-end mirror))
3987 (set-marker (yas/mirror-end mirror) (point))
3988 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
3989 ;; super-special advance
3990 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
3992 (defun yas/field-update-display (field snippet)
3993 "Much like `yas/mirror-update-display', but for fields"
3994 (when (yas/field-transform field)
3995 (let ((transformed (and (not (eq (yas/field-number field) 0))
3996 (yas/apply-transform field field)))
3998 (when (and transformed
3999 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4000 (yas/field-end field)))))
4001 (setf (yas/field-modified-p field) t)
4002 (goto-char (yas/field-start field))
4003 (yas/inhibit-overlay-hooks
4004 (insert transformed)
4005 (if (> (yas/field-end field) (point))
4006 (delete-region (point) (yas/field-end field))
4007 (set-marker (yas/field-end field) (point))
4008 (yas/advance-start-maybe (yas/field-next field) (point)))
4012 ;;; Post-command hooks:
4014 (defvar yas/post-command-runonce-actions nil
4015 "List of actions to run once in `post-command-hook'.
4017 Each element of this list looks like (FN . ARGS) where FN is
4018 called with ARGS as its arguments after the currently executing
4021 After all actions have been run, this list is emptied, and after
4022 that the rest of `yas/post-command-handler' runs.")
4024 (defun yas/post-command-handler ()
4025 "Handles various yasnippet conditions after each command."
4026 (when yas/post-command-runonce-actions
4028 (mapc #'(lambda (fn-and-args)
4029 (apply (car fn-and-args)
4031 yas/post-command-runonce-actions)
4032 (error (message "[yas] Problem running `yas/post-command-runonce-actions'!")))
4033 (setq yas/post-command-runonce-actions nil))
4034 (cond (yas/protection-violation
4035 (goto-char yas/protection-violation)
4036 (setq yas/protection-violation nil))
4037 ((eq 'undo this-command)
4039 ;; After undo revival the correct field is sometimes not
4040 ;; restored correctly, this condition handles that
4042 (let* ((snippet (car (yas/snippets-at-point)))
4043 (target-field (and snippet
4044 (find-if-not #'(lambda (field)
4045 (yas/field-probably-deleted-p snippet field))
4047 (cons (yas/snippet-active-field snippet)
4048 (yas/snippet-fields snippet)))))))
4050 (yas/move-to-field snippet target-field))))
4051 ((not (yas/undo-in-progress))
4052 ;; When not in an undo, check if we must commit the snippet
4053 ;; (user exited it).
4054 (yas/check-commit-snippet))))
4058 (put 'yas/expand 'function-documentation
4059 '(yas/expand-from-trigger-key-doc))
4060 (defun yas/expand-from-trigger-key-doc ()
4061 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4062 (let ((fallback-description
4063 (cond ((eq yas/fallback-behavior 'call-other-command)
4064 (let* ((yas/minor-mode nil)
4065 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4067 (format " call command `%s'." (pp-to-string fallback)))
4069 ((eq yas/fallback-behavior 'return-nil)
4072 ", defer to `yas/fallback-behaviour' :-)"))))
4073 (concat "Expand a snippet before point. If no snippet
4074 expansion is possible,"
4075 fallback-description
4076 "\n\nOptional argument FIELD is for non-interactive use and is an
4077 object satisfying `yas/field-p' to restrict the expansion to.")))
4079 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4080 (defun yas/expand-from-keymap-doc ()
4081 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4082 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4083 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4084 (when (eq this-command 'describe-key)
4085 (let* ((vec (this-single-command-keys))
4086 (templates (mapcan #'(lambda (table)
4087 (yas/fetch table vec))
4088 (yas/get-snippet-tables)))
4089 (yas/direct-keymaps nil)
4090 (fallback (key-binding vec)))
4091 (concat "In this case, "
4093 (concat "these snippets are bound to this key:\n"
4094 (yas/template-pretty-list templates)
4095 "\n\nIf none of these expands, "))
4097 (format "fallback `%s' will be called." (pp-to-string fallback)))
4098 "no fallback keybinding is called."))))))
4100 (defun yas/template-pretty-list (templates)
4102 (yas/buffer-local-condition 'always))
4103 (dolist (plate templates)
4104 (setq acc (concat acc "\n*) "
4105 (propertize (concat "\\\\snippet `" (car plate) "'")
4106 'yasnippet (cdr plate)))))
4109 (define-button-type 'help-snippet-def
4110 :supertype 'help-xref
4111 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4112 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4114 (defun yas/snippet-description-finish-runonce ()
4115 "Final adjustments for the help buffer when snippets are concerned."
4116 (yas/create-snippet-xrefs)
4117 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4119 (defun yas/create-snippet-xrefs ()
4121 (goto-char (point-min))
4122 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4123 (let ((template (get-text-property (match-beginning 1)
4126 (help-xref-button 1 'help-snippet-def template)
4127 (kill-region (match-end 1) (match-end 0))
4128 (kill-region (match-beginning 0) (match-beginning 1)))))))
4130 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4131 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4133 Remaining args as in `yas/expand-snippet'."
4134 (let* ((table (gethash mode-symbol yas/tables))
4135 (yas/current-template (and table
4136 (gethash uuid (yas/table-uuidhash table)))))
4137 (when yas/current-template
4138 (yas/expand-snippet (yas/template-content yas/current-template)))))
4143 ;; `locate-dominating-file'
4144 ;; `region-active-p'
4146 ;; added for compatibility in emacs < 23
4147 (unless (>= emacs-major-version 23)
4148 (unless (fboundp 'region-active-p)
4149 (defun region-active-p () (and transient-mark-mode mark-active)))
4151 (unless (fboundp 'locate-dominating-file)
4152 (defvar locate-dominating-stop-dir-regexp
4153 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4154 "Regexp of directory names which stop the search in `locate-dominating-file'.
4155 Any directory whose name matches this regexp will be treated like
4156 a kind of root directory by `locate-dominating-file' which will stop its search
4157 when it bumps into it.
4158 The default regexp prevents fruitless and time-consuming attempts to find
4159 special files in directories in which filenames are interpreted as hostnames,
4160 or mount points potentially requiring authentication as a different user.")
4162 (defun locate-dominating-file (file name)
4163 "Look up the directory hierarchy from FILE for a file named NAME.
4164 Stop at the first parent directory containing a file NAME,
4165 and return the directory. Return nil if not found."
4166 ;; We used to use the above locate-dominating-files code, but the
4167 ;; directory-files call is very costly, so we're much better off doing
4168 ;; multiple calls using the code in here.
4170 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4171 ;; `name' in /home or in /.
4172 (setq file (abbreviate-file-name file))
4175 ;; `user' is not initialized outside the loop because
4176 ;; `file' may not exist, so we may have to walk up part of the
4177 ;; hierarchy before we find the "initial UUID".
4180 (while (not (or root
4182 ;; FIXME: Disabled this heuristic because it is sometimes
4184 ;; As a heuristic, we stop looking up the hierarchy of
4185 ;; directories as soon as we find a directory belonging
4186 ;; to another user. This should save us from looking in
4187 ;; things like /net and /afs. This assumes that all the
4188 ;; files inside a project belong to the same user.
4189 ;; (let ((prev-user user))
4190 ;; (setq user (nth 2 (file-attributes file)))
4191 ;; (and prev-user (not (equal user prev-user))))
4192 (string-match locate-dominating-stop-dir-regexp file)))
4193 (setq try (file-exists-p (expand-file-name name file)))
4194 (cond (try (setq root file))
4195 ((equal file (setq prev-file file
4196 file (file-name-directory
4197 (directory-file-name file))))
4201 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4202 ;; (when it execute forward-char) and interrupt the after change
4203 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4204 ;; invoked. Here's a way to reproduce it:
4206 ;; # open a *new* Emacs.
4207 ;; # load yasnippet.
4208 ;; # open a *new* .cpp file.
4209 ;; # input "inc" and press TAB to expand the snippet.
4210 ;; # select the `#include <...>` snippet.
4211 ;; # type inside `<>`
4213 (defadvice c-neutralize-syntax-in-CPP
4214 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4215 "Adviced `c-neutralize-syntax-in-CPP' to properly
4216 handle the end-of-buffer error fired in it by calling
4217 `forward-char' at the end of buffer."
4220 (error (message (error-message-string err)))))
4222 ;; disable c-electric-* serial command in YAS fields
4223 (add-hook 'c-mode-common-hook
4225 (dolist (k '(":" ">" ";" "<" "{" "}"))
4226 (define-key (symbol-value (make-local-variable 'yas/keymap))
4227 k 'self-insert-command))))
4229 (provide 'yasnippet)
4231 ;;; yasnippet.el ends here