1 ;;; yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright (C) 2008-2012 Free Software Foundation, Inc.
4 ;; Authors: pluskid <pluskid@gmail.com>, João Távora <joaotavora@gmail.com>
6 ;; Package-version: 0.7.0
7 ;; X-URL: http://github.com/capitaomorte/yasnippet
8 ;; Keywords: convenience, emulation
9 ;; URL: http://github.com/capitaomorte/yasnippet
10 ;; EmacsWiki: YaSnippetMode
12 ;; This program is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
27 ;; Basic steps to setup:
29 ;; (add-to-list 'load-path
30 ;; "~/path-to-yasnippet")
31 ;; (require 'yasnippet)
32 ;; (yas/global-mode 1)
35 ;; Interesting variables are:
39 ;; The directory where user-created snippets are to be
40 ;; stored. Can also be a list of directories. In that case,
41 ;; when used for bulk (re)loading of snippets (at startup or
42 ;; via `yas/reload-all'), directories appearing earlier in
43 ;; the list shadow other dir's snippets. Also, the first
44 ;; directory is taken as the default for storing the user's
47 ;; The deprecated `yas/root-directory' aliases this variable
48 ;; for backward-compatibility.
52 ;; A local variable that you can set in a hook to override
53 ;; snippet-lookup based on major mode. It is a a symbol (or
54 ;; list of symbols) that correspond to subdirectories of
55 ;; `yas/snippet-dirs' and is used for deciding which
56 ;; snippets to consider for the active buffer.
58 ;; Deprecated `yas/mode-symbol' aliases this variable for
59 ;; backward-compatibility.
61 ;; Major commands are:
65 ;; Try to expand snippets before point. In `yas/minor-mode',
66 ;; this is bound to `yas/trigger-key' which you can customize.
68 ;; M-x yas/load-directory
70 ;; Prompts you for a directory hierarchy of snippets to load.
72 ;; M-x yas/insert-snippet
74 ;; Prompts you for possible snippet expansion if that is
75 ;; possible according to buffer-local and snippet-local
76 ;; expansion conditions. With prefix argument, ignore these
79 ;; M-x yas/visit-snippet-file
81 ;; Prompts you for possible snippet expansions like
82 ;; `yas/insert-snippet', but instead of expanding it, takes
83 ;; you directly to the snippet definition's file, if it
86 ;; M-x yas/new-snippet
88 ;; Lets you create a new snippet file in the correct
89 ;; subdirectory of `yas/snippet-dirs', according to the
92 ;; M-x yas/load-snippet-buffer
94 ;; When editing a snippet, this loads the snippet. This is
95 ;; bound to "C-c C-c" while in the `snippet-mode' editing
98 ;; M-x yas/tryout-snippet
100 ;; When editing a snippet, this opens a new empty buffer,
101 ;; sets it to the appropriate major mode and inserts the
102 ;; snippet there, so you can see what it looks like. This is
103 ;; bound to "C-c C-t" while in `snippet-mode'.
105 ;; M-x yas/describe-tables
107 ;; Lists known snippets in a separate buffer. User is
108 ;; prompted as to whether only the currently active tables
109 ;; are to be displayed, or all the tables for all major
112 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
113 ;; can optionally use it the preferred "prompting method", puting in
114 ;; your .emacs file, for example:
116 ;; (require 'dropdown-list)
117 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
119 ;; yas/completing-prompt))
121 ;; Also check out the customization group
123 ;; M-x customize-group RET yasnippet RET
125 ;; If you use the customization group to set variables
126 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
127 ;; "yasnippet.el" is present in the `load-path' *before* the
128 ;; `custom-set-variables' is executed in your .emacs file.
130 ;; For more information and detailed usage, refer to the project page:
131 ;; http://github.com/capitaomorte/yasnippet
140 ;;; User customizable variables
142 (defgroup yasnippet nil
143 "Yet Another Snippet extension"
146 (defvar yas/load-file-name load-file-name
147 "Store the filename that yasnippet.el was originally loaded from.")
148 (defcustom yas/snippet-dirs (remove nil
149 (list "~/.emacs.d/snippets"
150 (when yas/load-file-name
151 (concat (file-name-directory yas/load-file-name) "snippets"))))
152 "Directory or list of snippet dirs for each major mode.
154 The directory where user-created snippets are to be stored. Can
155 also be a list of directories. In that case, when used for
156 bulk (re)loading of snippets (at startup or via
157 `yas/reload-all'), directories appearing earlier in the list
158 shadow other dir's snippets. Also, the first directory is taken
159 as the default for storing the user's new snippets."
160 :type '(choice (string :tag "Single directory (string)")
161 (repeat :args (string) :tag "List of directories (strings)"))
164 :set #'(lambda (symbol new)
165 (let ((old (and (boundp symbol)
166 (symbol-value symbol))))
167 (set-default symbol new)
168 (unless (or (not (fboundp 'yas/reload-all))
171 (defun yas/snippet-dirs ()
172 "Returns `yas/snippet-dirs' (which see) as a list."
173 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
174 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
176 (defcustom yas/prompt-functions '(yas/x-prompt
178 yas/completing-prompt
181 "Functions to prompt for keys, templates, etc interactively.
183 These functions are called with the following arguments:
185 - PROMPT: A string to prompt the user
187 - CHOICES: a list of strings or objects.
189 - optional DISPLAY-FN : A function that, when applied to each of
190 the objects in CHOICES will return a string.
192 The return value of any function you put here should be one of
193 the objects in CHOICES, properly formatted with DISPLAY-FN (if
196 - To signal that your particular style of prompting is
197 unavailable at the moment, you can also have the function return
200 - To signal that the user quit the prompting process, you can
203 (signal 'quit \"user quit!\")."
204 :type '(repeat function)
207 (defcustom yas/indent-line 'auto
208 "Controls indenting applied to a recent snippet expansion.
210 The following values are possible:
212 - `fixed' Indent the snippet to the current column;
214 - `auto' Indent each line of the snippet with `indent-according-to-mode'
216 Every other value means don't apply any snippet-side indendation
217 after expansion (the manual per-line \"$>\" indentation still
219 :type '(choice (const :tag "Nothing" nothing)
220 (const :tag "Fixed" fixed)
221 (const :tag "Auto" auto))
224 (defcustom yas/also-auto-indent-first-line nil
225 "Non-nil means also auto indent first line according to mode.
227 Naturally this is only valid when `yas/indent-line' is `auto'"
231 (defcustom yas/snippet-revival t
232 "Non-nil means re-activate snippet fields after undo/redo."
236 (defcustom yas/trigger-key "TAB"
237 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
239 Value is a string that is converted to the internal Emacs key
240 representation using `read-kbd-macro'."
243 :set #'(lambda (symbol key)
244 (let ((old (and (boundp symbol)
245 (symbol-value symbol))))
246 (set-default symbol key)
247 ;; On very first loading of this defcustom,
248 ;; `yas/trigger-key' is *not* loaded.
249 (if (fboundp 'yas/trigger-key-reload)
250 (yas/trigger-key-reload old)))))
252 (defcustom yas/next-field-key '("TAB" "<tab>")
253 "The key to navigate to next field when a snippet is active.
255 Value is a string that is converted to the internal Emacs key
256 representation using `read-kbd-macro'.
258 Can also be a list of strings."
259 :type '(choice (string :tag "String")
260 (repeat :args (string) :tag "List of strings"))
262 :set #'(lambda (symbol val)
263 (set-default symbol val)
264 (if (fboundp 'yas/init-yas-in-snippet-keymap)
265 (yas/init-yas-in-snippet-keymap))))
268 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
269 "The key to navigate to previous field when a snippet is active.
271 Value is a string that is converted to the internal Emacs key
272 representation using `read-kbd-macro'.
274 Can also be a list of strings."
275 :type '(choice (string :tag "String")
276 (repeat :args (string) :tag "List of strings"))
278 :set #'(lambda (symbol val)
279 (set-default symbol val)
280 (if (fboundp 'yas/init-yas-in-snippet-keymap)
281 (yas/init-yas-in-snippet-keymap))))
283 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
284 "The key to clear the currently active field.
286 Value is a string that is converted to the internal Emacs key
287 representation using `read-kbd-macro'.
289 Can also be a list of strings."
290 :type '(choice (string :tag "String")
291 (repeat :args (string) :tag "List of strings"))
293 :set #'(lambda (symbol val)
294 (set-default symbol val)
295 (if (fboundp 'yas/init-yas-in-snippet-keymap)
296 (yas/init-yas-in-snippet-keymap))))
298 (defcustom yas/triggers-in-field nil
299 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
301 Otherwise, `yas/next-field-key' just tries to move on to the next
306 (defcustom yas/fallback-behavior 'call-other-command
307 "How to act when `yas/trigger-key' does *not* expand a snippet.
309 - `call-other-command' means try to temporarily disable YASnippet
310 and call the next command bound to `yas/trigger-key'.
312 - nil or the symbol `return-nil' mean do nothing. (and
313 `yas/expand-returns' nil)
315 - A lisp form (apply COMMAND . ARGS) means interactively call
316 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
317 with ARGS as arguments."
318 :type '(choice (const :tag "Call previous command" call-other-command)
319 (const :tag "Do nothing" return-nil))
322 (defcustom yas/choose-keys-first nil
323 "If non-nil, prompt for snippet key first, then for template.
325 Otherwise prompts for all possible snippet names.
327 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
331 (defcustom yas/choose-tables-first nil
332 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
334 Otherwise, user chooses between the merging together of all
337 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
341 (defcustom yas/use-menu 'abbreviate
342 "Display a YASnippet menu in the menu bar.
344 When non-nil, submenus for each snippet table will be listed
345 under the menu \"Yasnippet\".
347 - If set to `real-modes' only submenus whose name more or less
348 corresponds to a major mode are listed.
350 - If set to `abbreviate', only the current major-mode
351 menu and the modes set in `yas/extra-modes' are listed.
353 Any other non-nil value, every submenu is listed."
354 :type '(choice (const :tag "Full" t)
355 (const :tag "Real modes only" real-modes)
356 (const :tag "Abbreviate" abbreviate))
359 (defcustom yas/trigger-symbol " =>"
360 "The text that will be used in menu to represent the trigger."
364 (defcustom yas/wrap-around-region nil
365 "If non-nil, snippet expansion wraps around selected region.
367 The wrapping occurs just before the snippet's exit marker. This
368 can be overriden on a per-snippet basis."
372 (defcustom yas/good-grace t
373 "If non-nil, don't raise errors in inline elisp evaluation.
375 An error string \"[yas] error\" is returned instead."
379 (defcustom yas/visit-from-menu nil
380 "If non-nil visit snippets's files from menu, instead of expanding them.
382 This cafn only work when snippets are loaded from files."
386 (defcustom yas/expand-only-for-last-commands nil
387 "List of `last-command' values to restrict tab-triggering to, or nil.
389 Leave this set at nil (the default) to be able to trigger an
390 expansion simply by placing the cursor after a valid tab trigger,
391 using whichever commands.
393 Optionallly, set this to something like '(self-insert-command) if
394 you to wish restrict expansion to only happen when the last
395 letter of the snippet tab trigger was typed immediately before
396 the trigger key itself."
397 :type '(repeat function)
400 ;; Only two faces, and one of them shouldn't even be used...
402 (defface yas/field-highlight-face
403 '((t (:inherit 'region)))
404 "The face used to highlight the currently active field of a snippet"
407 (defface yas/field-debug-face
409 "The face used for debugging some overlays normally hidden"
413 ;;; User can also customize the next defvars
414 (defun yas/define-some-keys (keys keymap definition)
415 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
416 (let ((keys (or (and (listp keys) keys)
419 (define-key keymap (read-kbd-macro key) definition))))
422 (let ((map (make-sparse-keymap)))
423 (mapc #'(lambda (binding)
424 (yas/define-some-keys (car binding) map (cdr binding)))
425 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
426 (,yas/prev-field-key . yas/prev-field)
427 ("C-g" . yas/abort-snippet)
428 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
430 "The keymap active while a snippet expansion is in progress.")
432 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
433 "List of character syntaxes used to find a trigger key before point.
434 The list is tried in the order while scanning characters
435 backwards from point. For example, if the list is '(\"w\" \"w_\")
436 first look for trigger keys which are composed exclusively of
437 \"word\"-syntax characters, and then, if that fails, look for
438 keys which are either of \"word\" or \"symbol\"
439 syntax. Triggering after
443 will, according to the \"w\" element first try \"bar\". If that
444 isn't a trigger key, \"foo-bar\" is tried, respecting a second
447 (defvar yas/after-exit-snippet-hook
449 "Hooks to run after a snippet exited.
451 The hooks will be run in an environment where some variables bound to
454 `yas/snippet-beg' : The beginning of the region of the snippet.
456 `yas/snippet-end' : Similar to beg.
458 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
460 (defvar yas/before-expand-snippet-hook
462 "Hooks to run just before expanding a snippet.")
464 (defvar yas/buffer-local-condition
465 '(if (and (or (fourth (syntax-ppss))
466 (fifth (syntax-ppss)))
467 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
468 '(require-snippet-condition . force-in-comment)
470 "Snippet expanding condition.
472 This variable is a lisp form which is evaluated everytime a
473 snippet expansion is attemped:
475 * If it evaluates to nil, no snippets can be expanded.
477 * If it evaluates to the a cons (require-snippet-condition
480 * Snippets bearing no \"# condition:\" directive are not
483 * Snippets bearing conditions that evaluate to nil (or
484 produce an error) won't be onsidered.
486 * If the snippet has a condition that evaluates to non-nil
489 * If REQUIREMENT is t, the snippet is considered
491 * If REQUIREMENT is `eq' RESULT, the snippet is
494 * Otherwise, the snippet is not considered.
496 * If it evaluates to the symbol 'always, all snippets are
497 considered for expansion, regardless of any conditions.
499 * If it evaluates to t or some other non-nil value
501 * Snippet bearing no conditions, or conditions that
502 evaluate to non-nil, are considered for expansion.
504 * Otherwise, the snippet is not considered.
506 Here's an example preventing snippets from being expanded from
507 inside comments, in `python-mode' only, with the exception of
508 snippets returning the symbol 'force-in-comment in their
511 (add-hook 'python-mode-hook
513 (setq yas/buffer-local-condition
514 '(if (python-in-string/comment)
515 '(require-snippet-condition . force-in-comment)
518 The default value is similar, it filters out potential snippet
519 expansions inside comments and string literals, unless the
520 snippet itself contains a condition that returns the symbol
521 `force-in-comment'.")
524 ;;; Internal variables
526 (defvar yas/version "0.7.0 (beta)")
528 (defvar yas/menu-table (make-hash-table)
529 "A hash table of MAJOR-MODE symbols to menu keymaps.")
531 (defvar yas/known-modes
532 '(ruby-mode rst-mode markdown-mode)
533 "A list of mode which is well known but not part of emacs.")
535 (defvar yas/escaped-characters
536 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
537 "List of characters which *might* need to be escaped.")
539 (defconst yas/field-regexp
540 "${\\([0-9]+:\\)?\\([^}]*\\)}"
541 "A regexp to *almost* recognize a field.")
543 (defconst yas/multi-dollar-lisp-expression-regexp
544 "$+[ \t\n]*\\(([^)]*)\\)"
545 "A regexp to *almost* recognize a \"$(...)\" expression.")
547 (defconst yas/backquote-lisp-expression-regexp
549 "A regexp to recognize a \"`lisp-expression`\" expression." )
551 (defconst yas/transform-mirror-regexp
552 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
553 "A regexp to *almost* recognize a mirror with a transform.")
555 (defconst yas/simple-mirror-regexp
557 "A regexp to recognize a simple mirror.")
559 (defvar yas/snippet-id-seed 0
560 "Contains the next id for a snippet.")
562 (defun yas/snippet-next-id ()
563 (let ((id yas/snippet-id-seed))
564 (incf yas/snippet-id-seed)
570 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
571 (defvar last-buffer-undo-list nil)
573 (defvar yas/minor-mode-menu nil
574 "Holds the YASnippet menu")
576 (defun yas/init-minor-keymap ()
577 (let ((map (make-sparse-keymap)))
578 (easy-menu-define yas/minor-mode-menu
580 "Menu used when YAS/minor-mode is active."
583 ["Expand trigger" yas/expand
584 :help "Possibly expand tab trigger before point"]
585 ["Insert at point..." yas/insert-snippet
586 :help "Prompt for an expandable snippet and expand it at point"]
587 ["New snippet..." yas/new-snippet
588 :help "Create a new snippet in an appropriate directory"]
589 ["Visit snippet file..." yas/visit-snippet-file
590 :help "Prompt for an expandable snippet and find its file"]
592 ("Snippet menu behaviour"
593 ["Visit snippets" (setq yas/visit-from-menu t)
594 :help "Visit snippets from the menu"
595 :active t :style radio :selected yas/visit-from-menu]
596 ["Expand snippets" (setq yas/visit-from-menu nil)
597 :help "Expand snippets from the menu"
598 :active t :style radio :selected (not yas/visit-from-menu)]
600 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
601 :help "Show snippet submenus for modes that appear to be real major modes"
602 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
603 ["Show all modes" (setq yas/use-menu 't)
604 :help "Show one snippet submenu for each loaded table"
605 :active t :style radio :selected (eq yas/use-menu 't)]
606 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
607 :help "Show only snippet submenus for the current active modes"
608 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
610 ["Auto" (setq yas/indent-line 'auto)
611 :help "Indent each line of the snippet with `indent-according-to-mode'"
612 :active t :style radio :selected (eq yas/indent-line 'auto)]
613 ["Fixed" (setq yas/indent-line 'fixed)
614 :help "Indent the snippet to the current column"
615 :active t :style radio :selected (eq yas/indent-line 'fixed)]
616 ["None" (setq yas/indent-line 'none)
617 :help "Don't apply any particular snippet indentation after expansion"
618 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
620 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
621 (not yas/also-auto-indent-first-line))
622 :help "When auto-indenting also, auto indent the first line menu"
623 :active (eq yas/indent-line 'auto)
624 :style toggle :selected yas/also-auto-indent-first-line]
627 ["System X-widget" (setq yas/prompt-functions
629 (remove 'yas/x-prompt
630 yas/prompt-functions)))
631 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
632 :active t :style radio :selected (eq (car yas/prompt-functions)
634 ["Dropdown-list" (setq yas/prompt-functions
635 (cons 'yas/dropdown-prompt
636 (remove 'yas/dropdown-prompt
637 yas/prompt-functions)))
638 :help "Use a special dropdown list"
639 :active t :style radio :selected (eq (car yas/prompt-functions)
640 'yas/dropdown-prompt)]
641 ["Ido" (setq yas/prompt-functions
642 (cons 'yas/ido-prompt
643 (remove 'yas/ido-prompt
644 yas/prompt-functions)))
645 :help "Use an ido-style minibuffer prompt"
646 :active t :style radio :selected (eq (car yas/prompt-functions)
648 ["Completing read" (setq yas/prompt-functions
649 (cons 'yas/completing-prompt
650 (remove 'yas/completing-prompt-prompt
651 yas/prompt-functions)))
652 :help "Use a normal minibuffer prompt"
653 :active t :style radio :selected (eq (car yas/prompt-functions)
654 'yas/completing-prompt-prompt)]
657 ["Wrap region in exit marker"
658 (setq yas/wrap-around-region
659 (not yas/wrap-around-region))
660 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
661 :style toggle :selected yas/wrap-around-region]
662 ["Allow stacked expansions "
663 (setq yas/triggers-in-field
664 (not yas/triggers-in-field))
665 :help "If non-nil allow snippets to be triggered inside other snippet fields"
666 :style toggle :selected yas/triggers-in-field]
667 ["Revive snippets on undo "
668 (setq yas/snippet-revival
669 (not yas/snippet-revival))
670 :help "If non-nil allow snippets to become active again after undo"
671 :style toggle :selected yas/snippet-revival]
674 (not yas/good-grace))
675 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
676 :style toggle :selected yas/good-grace]
679 ["Load snippets..." yas/load-directory
680 :help "Load snippets from a specific directory"]
681 ["Reload everything" yas/reload-all
682 :help "Cleanup stuff, reload snippets, rebuild menus"]
684 :help "Display some information about YASsnippet"]))
685 ;; Now for the stuff that has direct keybindings
687 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
688 (define-key map "\C-c&\C-n" 'yas/new-snippet)
689 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
692 (defvar yas/minor-mode-map (yas/init-minor-keymap)
693 "The keymap used when `yas/minor-mode' is active.")
695 (defun yas/trigger-key-reload (&optional unbind-key)
696 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
698 With optional UNBIND-KEY, try to unbind that key from
699 `yas/minor-mode-map'."
700 (when (and unbind-key
702 (not (string= unbind-key "")))
703 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
704 (when (and yas/trigger-key
705 (stringp yas/trigger-key)
706 (not (string= yas/trigger-key "")))
707 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
709 (defvar yas/tables (make-hash-table)
710 "A hash table of mode symbols to `yas/table' objects.")
712 (defvar yas/parents (make-hash-table)
713 "A hash table of mode symbols do lists of direct parent mode symbols.
715 This list is populated when reading the \".yas-parents\" files
716 found when traversing snippet directories with
717 `yas/load-directory'.
719 There might be additionalal parenting information stored in the
720 `derived-mode-parent' property of some mode symbols, but that is
723 (defvar yas/direct-keymaps (list)
724 "Keymap alist supporting direct snippet keybindings.
726 This variable is is placed in `emulation-mode-map-alists'.
728 Its elements looks like (TABLE-NAME . KEYMAP). They're
729 instantiated on `yas/reload-all' but KEYMAP is added to only when
730 loading snippets. `yas//direct-TABLE-NAME' is then a variable set
731 buffer-locally when entering `yas/minor-mode'. KEYMAP binds all
732 defined direct keybindings to the command
733 `yas/expand-from-keymap' which then which snippet to expand.")
735 (defun yas/direct-keymaps-reload ()
736 "Force reload the direct keybinding for active snippet tables."
738 (setq yas/direct-keymaps nil)
739 (maphash #'(lambda (name table)
740 (push (cons (intern (format "yas//direct-%s" name))
741 (yas/table-direct-keymap table))
745 (defun yas/modes-to-activate ()
746 "Compute list of mode symbols that are active for `yas/expand'
748 (let ((modes-to-activate (list major-mode))
750 (while (setq mode (get mode 'derived-mode-parent))
751 (push mode modes-to-activate))
752 (dolist (mode (yas/extra-modes))
753 (push mode modes-to-activate))
755 (append modes-to-activate
756 (mapcan #'(lambda (mode)
757 (yas/all-parents mode))
758 modes-to-activate)))))
760 (defvar yas/minor-mode-hook nil
761 "Hook run when yas/minor-mode is turned on")
764 (define-minor-mode yas/minor-mode
765 "Toggle YASnippet mode.
767 When YASnippet mode is enabled, the `yas/trigger-key' key expands
768 snippets of code depending on the mode.
770 With no argument, this command toggles the mode.
771 positive prefix argument turns on the mode.
772 Negative prefix argument turns off the mode.
774 You can customize the key through `yas/trigger-key'.
777 \\{yas/minor-mode-map}"
779 ;; The indicator for the mode line.
782 (cond (yas/minor-mode
783 ;; Reload the trigger key
785 (yas/trigger-key-reload)
786 ;; Install the direct keymaps in `emulation-mode-map-alists'
787 ;; (we use `add-hook' even though it's not technically a hook,
788 ;; but it works). Then define variables named after modes to
789 ;; index `yas/direct-keymaps'.
791 ;; Also install the post-command-hook.
793 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
794 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
795 ;; Set the `yas//direct-%s' vars for direct keymap expansion
797 (dolist (mode (yas/modes-to-activate))
798 (let ((name (intern (format "yas//direct-%s" mode))))
799 (set-default name nil)
800 (set (make-local-variable name) t)))
803 (yas/load-pending-jits))
805 ;; Uninstall the direct keymaps and the post-command hook
807 (remove-hook 'post-command-hook 'yas/post-command-handler t)
808 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
811 (defvar yas/dont-activate '(minibufferp)
812 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
814 If a function, then its result is used.
816 If a list of functions, then all functions must return nil to
817 activate yas for this buffer.
819 `yas/minor-mode-on' is usually called by `yas/global-mode' so
820 this effectively lets you define exceptions to the \"global\"
821 behaviour. Can also be a function of zero arguments.")
822 (make-variable-buffer-local 'yas/dont-activate)
824 (defun yas/minor-mode-on ()
825 "Turn on YASnippet minor mode.
827 Do this unless `yas/dont-activate' is truish "
829 (unless (cond ((functionp yas/dont-activate)
830 (funcall yas/dont-activate))
831 ((consp yas/dont-activate)
832 (some #'funcall yas/dont-activate))
834 ;; Load all snippets definitions unless we still don't have a
835 ;; root-directory or some snippets have already been loaded.
840 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
844 (defadvice yas/global-mode (before yas/reload-with-jit (arg) activate)
848 ;; explicitly enabling
850 ((not yas/global-mode)
854 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
857 (defvar yas/font-lock-keywords
858 (append '(("^#.*$" . font-lock-comment-face))
859 lisp-font-lock-keywords
860 lisp-font-lock-keywords-1
861 lisp-font-lock-keywords-2
863 (0 font-lock-keyword-face)
864 (1 font-lock-string-face t))
866 (0 font-lock-keyword-face)
867 (1 font-lock-warning-face t))
868 ("${" font-lock-keyword-face)
869 ("$[0-9]+?" font-lock-preprocessor-face)
870 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
872 (0 font-lock-keyword-face)))))
874 (defun yas/init-major-keymap ()
875 (let ((map (make-sparse-keymap)))
876 (easy-menu-define nil
878 "Menu used when snippet-mode is active."
880 (mapcar #'(lambda (ent)
882 (define-key map (third ent) (second ent)))
883 (vector (first ent) (second ent) t))
885 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
886 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
889 (defvar snippet-mode-map
890 (yas/init-major-keymap)
891 "The keymap used when `snippet-mode' is active")
894 (define-derived-mode snippet-mode text-mode "Snippet"
895 "A mode for editing yasnippets"
896 (setq font-lock-defaults '(yas/font-lock-keywords))
897 (set (make-local-variable 'require-final-newline) nil)
898 (set (make-local-variable 'comment-start) "#")
899 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
903 ;;; Internal structs for template management
905 (defstruct (yas/template (:constructor yas/make-blank-template))
906 "A template for a snippet."
916 group ;; as dictated by the #group: directive or .yas-make-groups
917 perm-group ;; as dictated by `yas/define-menu'
921 (defun yas/populate-template (template &rest args)
922 "Helper function to populate a template with properties"
926 (position (intern (substring (symbol-name (car args)) 1))
927 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
929 (setq args (cddr args)))
932 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
933 "A table to store snippets for a particular mode.
935 Has the following fields:
939 A symbol name normally corresponding to a major mode, but can
940 also be a pseudo major-mode to be referenced in
941 `yas/extra-modes', for example.
945 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
946 a string or a vector, where the former is the snippet's trigger
947 and the latter means it's a direct keybinding. NAMEHASH is yet
948 another hash of (NAME . TEMPLATE) where NAME is the snippet's
949 name and TEMPLATE is a `yas/template' object.
951 `yas/table-direct-keymap'
953 A keymap for the snippets in this table that have direct
954 keybindings. This is kept in sync with the keyhash, i.e., all
955 the elements of the keyhash that are vectors appear here as
956 bindings to `yas/expand-from-keymap'.
960 A hash table mapping snippets uuid's to the same `yas/template'
961 objects. A snippet uuid defaults to the snippet's name.
964 (hash (make-hash-table :test 'equal))
965 (uuidhash (make-hash-table :test 'equal))
967 (direct-keymap (make-sparse-keymap)))
969 (defun yas/get-template-by-uuid (mode uuid)
970 "Find the snippet template in MODE by its UUID."
971 (let* ((table (gethash mode yas/tables mode)))
973 (gethash uuid (yas/table-uuidhash table)))))
975 ;; Apropos storing/updating in TABLE, this works in two steps:
977 ;; 1. `yas/remove-template-by-uuid' removes any
978 ;; keyhash-namehash-template mappings from TABLE, grabing the
979 ;; snippet by its uuid. Also removes mappings from TABLE's
980 ;; `yas/table-direct-keymap' (FIXME: and should probably take care
981 ;; of potentially stale menu bindings right?.)
983 ;; 2. `yas/add-template' adds this all over again.
985 ;; Create a new or add to an existing keyhash-namehash mapping.
987 ;; For reference on understanding this, consider three snippet
990 ;; A: # name: The Foo
992 ;; # binding: C-c M-l
994 ;; B: # name: Mrs Foo
997 ;; C: # name: The Bar
998 ;; # binding: C-c M-l
1003 ;; keyhash namehashes(3) yas/template structs(4)
1004 ;; -----------------------------------------------------
1007 ;; "foo" ---> "The Foo" ---> [yas/template A] |
1008 ;; "Mrs Foo" ---> [yas/template B] |
1010 ;; [C-c M-l] ---> "The Foo" -------------------------/
1011 ;; "The Bar" ---> [yas/template C]
1013 ;; "baz" ---> "Baz" ---> [yas/template D]
1015 ;; Additionally, since uuid defaults to the name, we have a
1016 ;; `yas/table-uuidhash' for TABLE
1018 ;; uuidhash yas/template structs
1019 ;; -------------------------------
1020 ;; "The Foo" ---> [yas/template A]
1021 ;; "Mrs Foo" ---> [yas/template B]
1022 ;; "The Bar" ---> [yas/template C]
1023 ;; "Baz" ---> [yas/template D]
1025 ;; FIXME: the more I look at this data-structure the more I think I'm
1026 ;; stupid. There has to be an easier way (but beware lots of code depends on this).
1028 (defun yas/remove-template-by-uuid (table uuid)
1029 "Remove from TABLE a template identified by UUID."
1030 (let ((template (gethash uuid (yas/table-uuidhash table))))
1032 (let* ((name (yas/template-name template))
1034 ;; Remove the name from each of the targeted namehashes
1036 (maphash #'(lambda (k v)
1037 (let ((template (gethash name v)))
1039 (eq uuid (yas/template-uuid template)))
1041 (when (zerop (hash-table-count v))
1042 (push k empty-keys)))))
1043 (yas/table-hash table))
1044 ;; Remove the namehash themselves if they've become empty
1046 (dolist (key empty-keys)
1048 (define-key (yas/table-direct-keymap table) key nil))
1049 (remhash key (yas/table-hash table)))
1051 ;; Finally, remove the uuid from the uuidhash
1053 (remhash uuid (yas/table-uuidhash table))))))
1055 (defun yas/add-template (table template)
1056 "Store in TABLE the snippet template TEMPLATE.
1058 KEY can be a string (trigger key) of a vector (direct
1060 (let ((name (yas/template-name template))
1061 (key (yas/template-key template))
1062 (keybinding (yas/template-keybinding template))
1063 (menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1064 (dolist (k (remove nil (list key keybinding)))
1068 (yas/table-hash table))
1070 (make-hash-table :test 'equal)
1071 (yas/table-hash table))))
1073 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1075 ;; Update trigger & keybinding in the menu-binding pair
1077 (unless (eq (cdr menu-binding-pair) :none)
1078 (setf (getf (cdr (car menu-binding-pair)) :keys)
1079 (or (and keybinding (key-description keybinding))
1080 (and key (concat key yas/trigger-symbol)))))
1082 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1084 (defun yas/update-template (table template)
1085 "Add or update TEMPLATE in TABLE.
1087 Also takes care of adding and updating to the associated menu."
1088 ;; Remove from table by uuid
1090 (yas/remove-template-by-uuid table (yas/template-uuid template))
1091 ;; Add to table again
1093 (yas/add-template table template)
1094 ;; Take care of the menu
1096 (let ((keymap (yas/menu-keymap-get-create table))
1097 (group (yas/template-group template)))
1098 (when (and yas/use-menu
1100 (not (cdr (yas/template-menu-binding-pair template))))
1101 ;; Remove from menu keymap
1103 (yas/delete-from-keymap keymap (yas/template-uuid template))
1105 ;; Add necessary subgroups as necessary.
1107 (dolist (subgroup group)
1108 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1109 (unless (and subgroup-keymap
1110 (keymapp subgroup-keymap))
1111 (setq subgroup-keymap (make-sparse-keymap))
1112 (define-key keymap (vector (make-symbol subgroup))
1113 `(menu-item ,subgroup ,subgroup-keymap)))
1114 (setq keymap subgroup-keymap)))
1116 ;; Add this entry to the keymap
1118 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1119 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1121 (defun yas/namehash-templates-alist (namehash)
1123 (maphash #'(lambda (k v)
1124 (push (cons k v) alist))
1128 (defun yas/fetch (table key)
1129 "Fetch templates in TABLE by KEY.
1131 Return a list of cons (NAME . TEMPLATE) where NAME is a
1132 string and TEMPLATE is a `yas/template' structure."
1133 (let* ((keyhash (yas/table-hash table))
1134 (namehash (and keyhash (gethash key keyhash))))
1136 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1139 ;;; Filtering/condition logic
1141 (defun yas/eval-condition (condition)
1148 (yas/message 1 "Error in condition evaluation: %s" (error-message-string err))
1152 (defun yas/filter-templates-by-condition (templates)
1153 "Filter the templates using the applicable condition.
1155 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1156 string and TEMPLATE is a `yas/template' structure.
1158 This function implements the rules described in
1159 `yas/buffer-local-condition'. See that variables documentation."
1160 (let ((requirement (yas/require-template-specific-condition-p)))
1161 (if (eq requirement 'always)
1163 (remove-if-not #'(lambda (pair)
1164 (yas/template-can-expand-p
1165 (yas/template-condition (cdr pair)) requirement))
1168 (defun yas/require-template-specific-condition-p ()
1169 "Decides if this buffer requests/requires snippet-specific
1170 conditions to filter out potential expansions."
1171 (if (eq 'always yas/buffer-local-condition)
1173 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1174 (yas/eval-condition yas/buffer-local-condition))
1175 yas/buffer-local-condition)))
1176 (when local-condition
1177 (if (eq local-condition t)
1179 (and (consp local-condition)
1180 (eq 'require-snippet-condition (car local-condition))
1181 (symbolp (cdr local-condition))
1182 (cdr local-condition)))))))
1184 (defun yas/template-can-expand-p (condition requirement)
1185 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1186 (let* ((result (or (null condition)
1187 (yas/eval-condition condition))))
1188 (cond ((eq requirement t)
1191 (eq requirement result)))))
1193 (defun yas/all-parents (mode)
1194 "Returns a list of all parent modes of MODE"
1195 (let ((parents (gethash mode yas/parents)))
1197 (mapcan #'yas/all-parents parents))))
1199 (defun yas/table-templates (table)
1202 (maphash #'(lambda (key namehash)
1203 (maphash #'(lambda (name template)
1204 (push (cons name template) acc))
1206 (yas/table-hash table))
1207 (yas/filter-templates-by-condition acc))))
1209 (defun yas/current-key ()
1210 "Get the key under current position. A key is used to find
1211 the template of a snippet in the current snippet-table."
1212 (let ((start (point))
1214 (syntaxes yas/key-syntaxes)
1218 (while (and (not done) syntaxes)
1219 (setq syntax (car syntaxes))
1220 (setq syntaxes (cdr syntaxes))
1222 (skip-syntax-backward syntax)
1223 (setq start (point)))
1225 (mapcan #'(lambda (table)
1226 (yas/fetch table (buffer-substring-no-properties start end)))
1227 (yas/get-snippet-tables)))
1236 (defun yas/table-all-keys (table)
1239 (maphash #'(lambda (key namehash)
1240 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1242 (yas/table-hash table))
1246 ;;; Internal functions
1248 (defun yas/real-mode? (mode)
1249 "Try to find out if MODE is a real mode. The MODE bound to
1250 a function (like `c-mode') is considered real mode. Other well
1251 known mode like `ruby-mode' which is not part of Emacs might
1252 not bound to a function until it is loaded. So yasnippet keeps
1253 a list of modes like this to help the judgement."
1255 (find mode yas/known-modes)))
1257 (defun yas/eval-lisp (form)
1258 "Evaluate FORM and convert the result to string."
1259 (let ((retval (catch 'yas/exception
1265 (let ((result (eval form)))
1267 (format "%s" result))))))
1268 (error (if yas/good-grace
1269 (yas/format "elisp error! %s" (error-message-string err))
1270 (error (yas/format "elisp error: %s"
1271 (error-message-string err)))))))))
1272 (when (and (consp retval)
1273 (eq 'yas/exception (car retval)))
1274 (error (cdr retval)))
1277 (defun yas/eval-lisp-no-saves (form)
1280 (error (if yas/good-grace
1281 (yas/format "elisp error! %s" (error-message-string err))
1282 (error (yas/format "elisp error: %s"
1283 (error-message-string err)))))))
1285 (defun yas/read-lisp (string &optional nil-on-error)
1286 "Read STRING as a elisp expression and return it.
1288 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1289 return an expression that when evaluated will issue an error."
1292 (error (and (not nil-on-error)
1293 `(error (error-message-string ,err))))))
1295 (defun yas/read-keybinding (keybinding)
1296 "Read KEYBINDING as a snippet keybinding, return a vector."
1297 (when (and keybinding
1298 (not (string-match "keybinding" keybinding)))
1300 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1302 (read-kbd-macro keybinding 'need-vector))))
1305 (yas/message 3 "warning: keybinding \"%s\" invalid since %s."
1306 keybinding (error-message-string err))
1309 (defvar yas/extra-modes nil
1310 "If non-nil, also lookup snippets for this/these modes.
1312 Can be a symbol or a list of symbols.
1314 This variable probably makes more sense as buffer-local, so
1315 ensure your use `make-local-variable' when you set it.")
1316 (defun yas/extra-modes ()
1317 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1318 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1320 (defun yas/table-get-create (mode)
1321 "Get or create the snippet table corresponding to MODE."
1322 (let ((table (gethash mode
1325 (setq table (yas/make-snippet-table (symbol-name mode)))
1326 (puthash mode table yas/tables)
1327 (push (cons (intern (format "yas//direct-%s" mode))
1328 (yas/table-direct-keymap table))
1329 yas/direct-keymaps))
1332 (defun yas/get-snippet-tables ()
1333 "Get snippet tables for current buffer.
1335 Return a list of `yas/table' objects. The list of modes to
1336 consider is returned by `yas/modes-to-activate'"
1338 (mapcar #'(lambda (mode-name)
1339 (gethash mode-name yas/tables))
1340 (yas/modes-to-activate))))
1342 (defun yas/menu-keymap-get-create (table)
1343 "Get or create the main menu keymap correspondong to MODE.
1345 This may very well create a plethora of menu keymaps and arrange
1346 them in all `yas/menu-table'"
1347 (let* ((mode (intern (yas/table-name table)))
1348 (menu-keymap (or (gethash mode yas/menu-table)
1349 (puthash mode (make-sparse-keymap) yas/menu-table)))
1350 (parents (yas/table-parents table)))
1351 (mapc #'yas/menu-keymap-get-create parents)
1352 (define-key yas/minor-mode-menu (vector mode)
1353 `(menu-item ,(symbol-name mode) ,menu-keymap
1354 :visible (yas/show-menu-p ',mode)))
1357 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1358 ;;; Template-related and snippet loading functions
1360 (defun yas/parse-template (&optional file)
1361 "Parse the template in the current buffer.
1363 Optional FILE is the absolute file name of the file being
1366 Optional GROUP is the group where the template is to go,
1367 otherwise we attempt to calculate it from FILE.
1369 Return a snippet-definition, i.e. a list
1371 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1373 If the buffer contains a line of \"# --\" then the contents above
1374 this line are ignored. Directives can set most of these with the syntax:
1376 # directive-name : directive-value
1378 Here's a list of currently recognized directives:
1389 (goto-char (point-min))
1390 (let* ((type 'snippet)
1392 (file-name-nondirectory file)))
1398 (yas/calculate-group file)))
1402 (if (re-search-forward "^# --\n" nil t)
1403 (progn (setq template
1404 (buffer-substring-no-properties (point)
1406 (setq bound (point))
1407 (goto-char (point-min))
1408 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1409 (when (string= "uuid" (match-string-no-properties 1))
1410 (setq uuid (match-string-no-properties 2)))
1411 (when (string= "type" (match-string-no-properties 1))
1412 (setq type (if (string= "command" (match-string-no-properties 2))
1415 (when (string= "key" (match-string-no-properties 1))
1416 (setq key (match-string-no-properties 2)))
1417 (when (string= "name" (match-string-no-properties 1))
1418 (setq name (match-string-no-properties 2)))
1419 (when (string= "condition" (match-string-no-properties 1))
1420 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1421 (when (string= "group" (match-string-no-properties 1))
1422 (setq group (match-string-no-properties 2)))
1423 (when (string= "expand-env" (match-string-no-properties 1))
1424 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1426 (when (string= "binding" (match-string-no-properties 1))
1427 (setq binding (match-string-no-properties 2)))))
1429 (buffer-substring-no-properties (point-min) (point-max))))
1430 (unless (or key binding)
1431 (setq key (and file (file-name-nondirectory file))))
1432 (when (eq type 'command)
1433 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1435 (setq group (split-string group "\\.")))
1436 (list key template name condition group expand-env file binding uuid)))
1438 (defun yas/calculate-group (file)
1439 "Calculate the group for snippet file path FILE."
1440 (let* ((dominating-dir (locate-dominating-file file
1441 ".yas-make-groups"))
1442 (extra-path (and dominating-dir
1443 (replace-regexp-in-string (concat "^"
1444 (expand-file-name dominating-dir))
1446 (expand-file-name file))))
1447 (extra-dir (and extra-path
1448 (file-name-directory extra-path)))
1449 (group (and extra-dir
1450 (replace-regexp-in-string "/"
1452 (directory-file-name extra-dir)))))
1455 (defun yas/subdirs (directory &optional filep)
1456 "Return subdirs or files of DIRECTORY according to FILEP."
1457 (remove-if (lambda (file)
1458 (or (string-match "^\\."
1459 (file-name-nondirectory file))
1460 (string-match "^#.*#$"
1461 (file-name-nondirectory file))
1463 (file-name-nondirectory file))
1465 (file-directory-p file)
1466 (not (file-directory-p file)))))
1467 (directory-files directory t)))
1469 (defun yas/make-menu-binding (template)
1470 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1471 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1473 (defun yas/expand-or-visit-from-menu (mode uuid)
1474 (let* ((table (yas/table-get-create mode))
1475 (yas/current-template (and table
1476 (gethash uuid (yas/table-uuidhash table)))))
1477 (when yas/current-template
1478 (if yas/visit-from-menu
1479 (yas/visit-snippet-file-1 yas/current-template)
1480 (let ((where (if (region-active-p)
1481 (cons (region-beginning) (region-end))
1482 (cons (point) (point)))))
1483 (yas/expand-snippet (yas/template-content yas/current-template)
1486 (yas/template-expand-env yas/current-template)))))))
1488 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1489 ;; Popping up for keys and templates
1491 (defvar yas/x-pretty-prompt-templates nil
1492 "If non-nil, attempt to prompt for templates like TextMate.")
1495 (defun yas/prompt-for-template (templates &optional prompt)
1496 "Interactively choose a template from the list TEMPLATES.
1498 TEMPLATES is a list of `yas/template'."
1501 (sort templates #'(lambda (t1 t2)
1502 (< (length (yas/template-name t1))
1503 (length (yas/template-name t2))))))
1504 (if yas/x-pretty-prompt-templates
1505 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1506 (some #'(lambda (fn)
1507 (funcall fn (or prompt "Choose a snippet: ")
1509 #'yas/template-name))
1510 yas/prompt-functions))))
1512 (defun yas/prompt-for-keys (keys &optional prompt)
1513 "Interactively choose a template key from the list KEYS."
1515 (some #'(lambda (fn)
1516 (funcall fn (or prompt "Choose a snippet key: ") keys))
1517 yas/prompt-functions)))
1519 (defun yas/prompt-for-table (tables &optional prompt)
1521 (some #'(lambda (fn)
1522 (funcall fn (or prompt "Choose a snippet table: ")
1525 yas/prompt-functions)))
1527 (defun yas/x-prompt (prompt choices &optional display-fn)
1528 "Display choices in a x-window prompt."
1529 ;; FIXME: HACK: if we notice that one of the objects in choices is
1530 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1532 ;; This would be better implemented by passing CHOICES as a
1533 ;; strucutred tree rather than a list. Modifications would go as far
1534 ;; up as `yas/all-templates' I think.
1536 (when (and window-system choices)
1538 (let (menu d) ;; d for display
1540 (setq d (or (and display-fn (funcall display-fn c))
1543 (push (cons (concat " " d) c) menu))
1545 (push (car d) menu))))
1546 (setq menu (list prompt (push "title" menu)))
1547 (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)
1557 (defun yas/x-pretty-prompt-templates (prompt templates)
1558 "Display TEMPLATES, grouping neatly by table name."
1559 (let ((organized (make-hash-table :test #'equal))
1563 (dolist (tl templates)
1564 (puthash (yas/template-table tl)
1566 (gethash (yas/template-table tl) organized))
1568 (setq more-than-one-table (> (hash-table-count organized) 1))
1569 (setq prefix (if more-than-one-table
1571 (if more-than-one-table
1572 (maphash #'(lambda (table templates)
1573 (push (yas/table-name table) menu)
1574 (dolist (tl templates)
1575 (push (cons (concat prefix (yas/template-name tl)) tl) menu))) organized)
1576 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas/template-name tl)) tl)) templates)))
1578 (setq menu (nreverse menu))
1579 (or (x-popup-menu (if (fboundp 'posn-at-point)
1580 (let ((x-y (posn-x-y (posn-at-point (point)))))
1581 (list (list (+ (car x-y) 10)
1585 (list prompt (push "title" menu)))
1588 (defun yas/ido-prompt (prompt choices &optional display-fn)
1589 (when (and (fboundp 'ido-completing-read)
1590 (or (>= emacs-major-version 24)
1592 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1594 (eval-when-compile (require 'dropdown-list nil t))
1595 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1596 (when (featurep 'dropdown-list)
1597 (let (formatted-choices
1601 (dolist (choice choices)
1602 (setq d (or (and display-fn (funcall display-fn choice))
1605 (push d formatted-choices)
1606 (push choice filtered-choices)))
1608 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1610 (nth n filtered-choices)
1613 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1614 (let (formatted-choices
1618 (completion-fn (or completion-fn
1619 #'completing-read)))
1620 (dolist (choice choices)
1621 (setq d (or (and display-fn (funcall display-fn choice))
1624 (push d formatted-choices)
1625 (push choice filtered-choices)))
1626 (setq chosen (and formatted-choices
1627 (funcall completion-fn prompt
1633 (let ((position (or (and chosen
1634 (position chosen formatted-choices :test #'string=))
1636 (nth position filtered-choices))))
1638 (defun yas/no-prompt (prompt choices &optional display-fn)
1641 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1642 ;; Loading snippets from files
1644 (defun yas/load-yas-setup-file (file)
1645 (load file 'noerror))
1647 (defun yas/load-directory (top-level-dir &optional use-jit)
1648 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1650 Below TOP-LEVEL-DIR each directory should be a mode name.
1652 Optional USE-JIT use jit-loading of snippets."
1653 (interactive "DSelect the root directory: ")
1654 (unless yas/snippet-dirs
1655 (setq yas/snippet-dirs top-level-dir))
1656 (dolist (dir (yas/subdirs top-level-dir))
1657 (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents
1658 (concat dir "/dummy")))
1659 (mode-sym (car major-mode-and-parents))
1660 (parents (cdr major-mode-and-parents)))
1661 (yas/define-parents mode-sym parents)
1662 (let ((form `(yas/load-directory-1 ,dir
1666 (yas/schedule-jit mode-sym form)
1668 (when (interactive-p)
1669 (yas/message 3 "Loaded snippets from %s." top-level-dir)))
1671 (defun yas/load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1672 "Recursively load snippet templates from DIRECTORY."
1673 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1674 (if (and (not no-compiled-snippets)
1675 (progn (yas/message 2 "Loading compiled snippets from %s" directory) t)
1676 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas/verbosity 3)))
1677 (yas/message 2 "Loading snippet files from %s" directory)
1678 (yas/load-directory-2 directory mode-sym))))
1680 (defun yas/load-directory-2 (directory mode-sym)
1681 ;; Load .yas-setup.el files wherever we find them
1683 (yas/load-yas-setup-file (expand-file-name ".yas-setup" directory))
1684 (let* ((default-directory directory)
1686 ;; load the snippet files
1689 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1690 (when (file-readable-p file)
1691 (insert-file-contents file nil nil nil t)
1692 (push (yas/parse-template file)
1695 (yas/define-snippets mode-sym
1697 ;; now recurse to a lower level
1699 (dolist (subdir (yas/subdirs directory))
1700 (yas/load-directory-2 subdir
1703 (defun yas/load-snippet-dirs (&optional nojit)
1704 "Reload the directories listed in `yas/snippet-dirs' or
1705 prompt the user to select one."
1707 (if yas/snippet-dirs
1708 (dolist (directory (reverse (yas/snippet-dirs)))
1709 (cond ((file-directory-p directory)
1710 (yas/load-directory directory (not nojit))
1712 (yas/message 3 "Loaded %s" directory)
1713 (yas/message 3 "Prepared just-in-time loading for %s" directory)))
1715 (push (yas/message 0 "Check your `yas/snippet-dirs': %s is not a directory" directory) errors))))
1716 (call-interactively 'yas/load-directory))
1719 (defun yas/reload-all (&optional interactive)
1720 "Reload all snippets and rebuild the YASnippet menu.
1722 When called interactively force immediate reload of all known
1723 snippets under `yas/snippet-dirs', otherwise use just-in-time
1728 (snippet-editing-buffers
1729 (remove-if-not #'(lambda (buffer)
1730 (with-current-buffer buffer yas/editing-template))
1732 ;; Warn if there are buffers visiting snippets, since reloading will break
1733 ;; any on-line editing of those buffers.
1735 (when snippet-editing-buffers
1737 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1738 (mapc #'kill-buffer snippet-editing-buffers)
1739 (yas/message 1 "Aborted reload...")
1741 ;; in a non-interactive use, at least set
1742 ;; `yas/editing-template' to nil, make it guess it next time around
1743 (mapc #'(lambda (buffer) (setq yas/editing-template nil)) (buffer-list))))
1745 ;; Empty all snippet tables, parenting info and all menu tables
1747 (setq yas/tables (make-hash-table))
1748 (setq yas/parents (make-hash-table))
1749 (setq yas/menu-table (make-hash-table))
1751 ;; Cancel all pending 'yas/scheduled-jit-loads'
1753 (setq yas/scheduled-jit-loads (make-hash-table))
1755 ;; Init the `yas/minor-mode-map', taking care not to break the
1758 (setf (cdr yas/minor-mode-map)
1759 (cdr (yas/init-minor-keymap)))
1761 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1762 ;; the user to select one.
1764 (setq errors (yas/load-snippet-dirs interactive))
1765 ;; Reload the direct keybindings
1767 (yas/direct-keymaps-reload)
1768 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1770 (yas/trigger-key-reload)
1772 (yas/message 3 "Reloaded everything%s...%s."
1773 (if interactive "" " (snippets will load just-in-time)")
1774 (if errors " (some errors, check *Messages*)" "")))))
1776 (defun yas/load-pending-jits ()
1777 (when yas/minor-mode
1778 (dolist (mode (yas/modes-to-activate))
1779 (let ((forms (gethash mode yas/scheduled-jit-loads)))
1780 (dolist (form forms)
1781 (yas/message 3 "Loading for `%s', just-in-time: %s!" mode form)
1783 (remhash mode yas/scheduled-jit-loads)))))
1785 ;; (when (<= emacs-major-version 22)
1786 ;; (add-hook 'after-change-major-mode-hook 'yas/load-pending-jits))
1788 (defun yas/quote-string (string)
1789 "Escape and quote STRING.
1790 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1792 (replace-regexp-in-string "[\\\"]"
1797 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1798 ;;; Snippet compilation function
1800 (defun yas/initialize ()
1801 "For backward compatibility, enable `yas/minor-mode' globally"
1802 (yas/global-mode 1))
1804 (defun yas/compile-directory (top-level-dir)
1805 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1807 This works by stubbing a few functions, then calling
1808 `yas/load-directory'."
1809 (interactive "DTop level snippet directory?")
1810 (flet ((yas/load-yas-setup-file
1812 (let ((elfile (concat file ".el")))
1813 (when (file-exists-p elfile)
1814 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1815 (insert-file-contents elfile)
1818 (yas/define-snippets
1820 (insert ";;; Snippet definitions:\n;;;\n")
1821 (let ((literal-snippets (list))
1823 (dolist (snippet snippets)
1824 (let ((key (first snippet))
1825 (template-content (second snippet))
1826 (name (third snippet))
1827 (condition (fourth snippet))
1828 (group (fifth snippet))
1829 (expand-env (sixth snippet))
1830 (file nil) ;; (seventh snippet)) ;; omit on purpose
1831 (binding (eighth snippet))
1832 (uuid (ninth snippet)))
1843 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets)))
1845 (yas/load-directory-1
1846 (dir mode parents &rest ignore)
1847 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1848 (with-temp-file output-file
1849 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1850 (yas/load-directory-2 dir mode)
1851 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1852 (yas/load-directory top-level-dir nil)))
1854 (defun yas/recompile-all ()
1855 "Compile every dir in `yas/snippet-dirs'."
1857 (mapc #'yas/compile-directory (yas/snippet-dirs)))
1863 (defvar yas/scheduled-jit-loads (make-hash-table)
1864 "Alist of mode-symbols to forms to be evaled when `yas/minor-mode' kicks in.")
1866 (defun yas/schedule-jit (mode form)
1869 (gethash mode yas/scheduled-jit-loads))
1870 yas/scheduled-jit-loads))
1873 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1874 ;;; Some user level functions
1879 (message (concat "yasnippet (version "
1881 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1883 (defun yas/define-parents (mode parents)
1884 "Add PARENTS to the list of MODE's parents"
1885 (puthash mode-sym (remove-duplicates
1887 (gethash mode-sym yas/parents)))
1890 (defun yas/define-snippets (mode snippets)
1891 "Define SNIPPETS for MODE.
1893 SNIPPETS is a list of snippet definitions, each taking the
1896 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1898 Within these, only KEY and TEMPLATE are actually mandatory.
1900 TEMPLATE might be a lisp form or a string, depending on whether
1901 this is a snippet or a snippet-command.
1903 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1904 been `yas/read-lisp'-ed and will eventually be
1907 The remaining elements are strings.
1909 FILE is probably of very little use if you're programatically
1912 UUID is the snippets \"unique-id\". Loading a second snippet file
1913 with the same uuid replaced the previous snippet.
1915 You can use `yas/parse-template' to return such lists based on
1916 the current buffers contents."
1917 (let ((snippet-table (yas/table-get-create mode))
1919 (dolist (snippet snippets)
1920 (setq template (yas/define-snippets-1 snippet
1924 (defun yas/define-snippets-1 (snippet snippet-table)
1925 "Helper for `yas/define-snippets'."
1926 ;; X) Calculate some more defaults on the values returned by
1927 ;; `yas/parse-template'.
1929 (let* ((file (seventh snippet))
1931 (name (or (third snippet)
1933 (file-name-directory file))))
1934 (condition (fourth snippet))
1935 (group (fifth snippet))
1936 (keybinding (yas/read-keybinding (eighth snippet)))
1937 (uuid (or (ninth snippet)
1939 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1940 (yas/make-blank-template))))
1941 ;; X) populate the template object
1943 (yas/populate-template template
1944 :table snippet-table
1946 :content (second snippet)
1949 :condition condition
1950 :expand-env (sixth snippet)
1951 :file (seventh snippet)
1952 :keybinding keybinding
1954 ;; X) Update this template in the appropriate table. This step
1955 ;; also will take care of adding the key indicators in the
1956 ;; templates menu entry, if any
1958 (yas/update-template snippet-table template)
1959 ;; X) Return the template
1964 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1965 "Get TEMPLATE's menu binding or assign it a new one.
1967 TYPE may be `:stay', signalling this menu binding should be
1968 static in the menu."
1969 (or (yas/template-menu-binding-pair template)
1970 (let ((key (yas/template-key template))
1971 (keybinding (yas/template-keybinding template)))
1972 (setf (yas/template-menu-binding-pair template)
1973 (cons `(menu-item ,(or (yas/template-name template)
1974 (yas/template-uuid template))
1975 ,(yas/make-menu-binding template)
1979 (defun yas/show-menu-p (mode)
1980 (cond ((eq yas/use-menu 'abbreviate)
1982 (mapcar #'(lambda (table)
1983 (intern (yas/table-name table)))
1984 (yas/get-snippet-tables))))
1985 ((eq yas/use-menu 'real-modes)
1986 (yas/real-mode? mode))
1990 (defun yas/delete-from-keymap (keymap uuid)
1991 "Recursively delete items with UUID from KEYMAP and its submenus."
1993 ;; XXX: This used to skip any submenus named \"parent mode\"
1995 ;; First of all, recursively enter submenus, i.e. the tree is
1996 ;; searched depth first so that stale submenus can be found in the
1999 (mapc #'(lambda (item)
2000 (when (and (listp (cdr item))
2001 (keymapp (third (cdr item))))
2002 (yas/delete-from-keymap (third (cdr item)) uuid)))
2004 ;; Set the uuid entry to nil
2006 (define-key keymap (vector (make-symbol uuid)) nil)
2007 ;; Destructively modify keymap
2009 (setcdr keymap (delete-if #'(lambda (item)
2010 (or (null (cdr item))
2011 (and (keymapp (third (cdr item)))
2012 (null (cdr (third (cdr item)))))))
2015 (defun yas/define-menu (mode menu omit-items)
2016 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2018 MENU is a list, its elements can be:
2020 - (yas/item UUID) : Creates an entry the snippet identified with
2021 UUID. The menu entry for a snippet thus identified is
2022 permanent, i.e. it will never move (be reordered) in the menu.
2024 - (yas/separator) : Creates a separator
2026 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
2027 SUBMENU has the same form as MENU. NAME is also added to the
2028 list of groups of the snippets defined thereafter.
2030 OMIT-ITEMS is a list of snippet uuid's that will always be
2031 ommited from MODE's menu, even if they're manually loaded.
2033 (let* ((table (yas/table-get-create mode))
2034 (hash (yas/table-uuidhash table)))
2035 (yas/define-menu-1 table
2036 (yas/menu-keymap-get-create table)
2039 (dolist (uuid omit-items)
2040 (let ((template (or (gethash uuid hash)
2041 (yas/populate-template (puthash uuid
2042 (yas/make-blank-template)
2046 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
2048 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
2049 (dolist (e (reverse menu))
2050 (cond ((eq (first e) 'yas/item)
2051 (let ((template (or (gethash (second e) uuidhash)
2052 (yas/populate-template (puthash (second e)
2053 (yas/make-blank-template)
2056 :perm-group group-list
2057 :uuid (second e)))))
2058 (define-key keymap (vector (gensym))
2059 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2060 ((eq (first e) 'yas/submenu)
2061 (let ((subkeymap (make-sparse-keymap)))
2062 (define-key keymap (vector (gensym))
2063 `(menu-item ,(second e) ,subkeymap))
2064 (yas/define-menu-1 table
2068 (append group-list (list (second e))))))
2069 ((eq (first e) 'yas/separator)
2070 (define-key keymap (vector (gensym))
2071 '(menu-item "----")))
2073 (yas/message 3 "Don't know anything about menu entry %s" (first e))))))
2075 (defun yas/define (mode key template &optional name condition group)
2076 "Define a snippet. Expanding KEY into TEMPLATE.
2078 NAME is a description to this template. Also update the menu if
2079 `yas/use-menu' is `t'. CONDITION is the condition attached to
2080 this snippet. If you attach a condition to a snippet, then it
2081 will only be expanded when the condition evaluated to non-nil."
2082 (yas/define-snippets mode
2083 (list (list key template name condition group))))
2085 (defun yas/hippie-try-expand (first-time?)
2086 "Integrate with hippie expand. Just put this function in
2087 `hippie-expand-try-functions-list'."
2088 (when yas/minor-mode
2089 (if (not first-time?)
2090 (let ((yas/fallback-behavior 'return-nil))
2096 ;;; Apropos condition-cache:
2101 (defvar yas/condition-cache-timestamp nil)
2102 (defmacro yas/define-condition-cache (func doc &rest body)
2103 "Define a function FUNC with doc DOC and body BODY, BODY is
2104 executed at most once every snippet expansion attempt, to check
2105 expansion conditions.
2107 It doesn't make any sense to call FUNC programatically."
2108 `(defun ,func () ,(if (and doc
2111 "\n\nFor use in snippets' conditions. Within each
2112 snippet-expansion routine like `yas/expand', computes actual
2113 value for the first time then always returns a cached value.")
2114 (setq body (cons doc body))
2116 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2117 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2118 (cdr timestamp-and-value)
2119 (let ((new-value (progn
2122 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2125 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2126 (defun yas/expand-from-trigger-key (&optional field)
2127 "Expand a snippet before point.
2129 If no snippet expansion is possible, fall back to the behaviour
2130 defined in `yas/fallback-behavior'.
2132 Optional argument FIELD is for non-interactive use and is an
2133 object satisfying `yas/field-p' to restrict the expansion to."
2135 (setq yas/condition-cache-timestamp (current-time))
2136 (let (templates-and-pos)
2137 (unless (and yas/expand-only-for-last-commands
2138 (not (member last-command yas/expand-only-for-last-commands)))
2139 (setq templates-and-pos (if field
2141 (narrow-to-region (yas/field-start field)
2142 (yas/field-end field))
2144 (yas/current-key))))
2145 (if (and templates-and-pos
2146 (first templates-and-pos))
2147 (yas/expand-or-prompt-for-template (first templates-and-pos)
2148 (second templates-and-pos)
2149 (third templates-and-pos))
2150 (yas/fallback 'trigger-key))))
2152 (defun yas/expand-from-keymap ()
2153 "Directly expand some snippets, searching `yas/direct-keymaps'.
2155 If expansion fails, execute the previous binding for this key"
2157 (setq yas/condition-cache-timestamp (current-time))
2158 (let* ((yas/prefix current-prefix-arg)
2159 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2160 universal-argument-num-events
2162 (templates (mapcan #'(lambda (table)
2163 (yas/fetch table vec))
2164 (yas/get-snippet-tables))))
2166 (yas/expand-or-prompt-for-template templates)
2167 (let ((yas/fallback-behavior 'call-other-command))
2170 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2171 "Expand one of TEMPLATES from START to END.
2173 Prompt the user if TEMPLATES has more than one element, else
2174 expand immediately. Common gateway for
2175 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2176 (let ((yas/current-template (or (and (rest templates) ;; more than one
2177 (yas/prompt-for-template (mapcar #'cdr templates)))
2179 (when yas/current-template
2180 (yas/expand-snippet (yas/template-content yas/current-template)
2183 (yas/template-expand-env yas/current-template)))))
2185 (defun yas/fallback (&optional from-trigger-key-p)
2186 "Fallback after expansion has failed.
2188 Common gateway for `yas/expand-from-trigger-key' and
2189 `yas/expand-from-keymap'."
2190 (cond ((eq yas/fallback-behavior 'return-nil)
2193 ((eq yas/fallback-behavior 'call-other-command)
2194 (let* ((yas/minor-mode nil)
2195 (yas/direct-keymaps nil)
2196 (keys-1 (this-command-keys-vector))
2197 (keys-2 (and yas/trigger-key
2199 (stringp yas/trigger-key)
2200 (read-kbd-macro yas/trigger-key)))
2201 (command-1 (and keys-1 (key-binding keys-1)))
2202 (command-2 (and keys-2 (key-binding keys-2)))
2203 ;; An (ugly) safety: prevents infinite recursion of
2204 ;; yas/expand* calls.
2205 (command (or (and (symbolp command-1)
2206 (not (string-match "yas/expand" (symbol-name command-1)))
2208 (and (symbolp command-2)
2210 (when (and (commandp command)
2211 (not (string-match "yas/expand" (symbol-name command))))
2212 (setq this-command command)
2213 (call-interactively command))))
2214 ((and (listp yas/fallback-behavior)
2215 (cdr yas/fallback-behavior)
2216 (eq 'apply (car yas/fallback-behavior)))
2217 (if (cddr yas/fallback-behavior)
2218 (apply (cadr yas/fallback-behavior)
2219 (cddr yas/fallback-behavior))
2220 (when (commandp (cadr yas/fallback-behavior))
2221 (setq this-command (cadr yas/fallback-behavior))
2222 (call-interactively (cadr yas/fallback-behavior)))))
2224 ;; also return nil if all the other fallbacks have failed
2229 ;;; Snippet development
2231 (defun yas/all-templates (tables)
2232 "Return all snippet tables applicable for the current buffer.
2234 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2235 `yas/buffer-local-condition'"
2236 (when yas/choose-tables-first
2237 (setq tables (list (yas/prompt-for-table tables))))
2239 (if yas/choose-keys-first
2240 (let ((key (yas/prompt-for-keys
2241 (mapcan #'yas/table-all-keys tables))))
2243 (mapcan #'(lambda (table)
2244 (yas/fetch table key))
2246 (remove-duplicates (mapcan #'yas/table-templates tables)
2249 (defun yas/insert-snippet (&optional no-condition)
2250 "Choose a snippet to expand, pop-up a list of choices according
2251 to `yas/prompt-function'.
2253 With prefix argument NO-CONDITION, bypass filtering of snippets
2256 (setq yas/condition-cache-timestamp (current-time))
2257 (let* ((yas/buffer-local-condition (or (and no-condition
2259 yas/buffer-local-condition))
2260 (templates (yas/all-templates (yas/get-snippet-tables)))
2261 (yas/current-template (and templates
2262 (or (and (rest templates) ;; more than one template for same key
2263 (yas/prompt-for-template templates))
2265 (where (if (region-active-p)
2266 (cons (region-beginning) (region-end))
2267 (cons (point) (point)))))
2268 (if yas/current-template
2269 (yas/expand-snippet (yas/template-content yas/current-template)
2272 (yas/template-expand-env yas/current-template))
2273 (yas/message 3 "No snippets can be inserted here!"))))
2275 (defun yas/visit-snippet-file ()
2276 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2278 Only success if selected snippet was loaded from a file. Put the
2279 visited file in `snippet-mode'."
2281 (let* ((yas/buffer-local-condition 'always)
2282 (templates (yas/all-templates (yas/get-snippet-tables)))
2283 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2284 (template (and templates
2285 (or (yas/prompt-for-template templates
2286 "Choose a snippet template to edit: ")
2290 (yas/visit-snippet-file-1 template)
2291 (message "No snippets tables active!"))))
2293 (defun yas/visit-snippet-file-1 (template)
2294 (let ((file (yas/template-file template)))
2295 (cond ((and file (file-readable-p file))
2296 (find-file-other-window file)
2298 (set (make-local-variable 'yas/editing-template) template))
2300 (message "Original file %s no longer exists!" file))
2302 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2303 (let ((type 'snippet))
2304 (when (listp (yas/template-content template))
2305 (insert (format "# type: command\n"))
2306 (setq type 'command))
2307 (insert (format "# key: %s\n" (yas/template-key template)))
2308 (insert (format "# name: %s\n" (yas/template-name template)))
2309 (when (yas/template-keybinding template)
2310 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2311 (when (yas/template-expand-env template)
2312 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2313 (when (yas/template-condition template)
2314 (insert (format "# condition: %s\n" (yas/template-condition template))))
2316 (insert (if (eq type 'command)
2317 (pp-to-string (yas/template-content template))
2318 (yas/template-content template))))
2320 (set (make-local-variable 'yas/editing-template) template)))))
2322 (defun yas/guess-snippet-directories-1 (table)
2323 "Guesses possible snippet subdirectories for TABLE."
2324 (cons (yas/table-name table)
2325 (mapcan #'(lambda (parent)
2326 (yas/guess-snippet-directories-1
2328 (yas/table-parents table))))
2330 (defun yas/guess-snippet-directories (&optional table)
2331 "Try to guess suitable directories based on the current active
2332 tables (or optional TABLE).
2334 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2335 `yas/table' object and DIRS is a list of all possible directories
2336 where snippets of table might exist."
2337 (let ((main-dir (replace-regexp-in-string
2339 (or (first (or (yas/snippet-dirs)
2340 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2341 (tables (or (and table
2343 (yas/get-snippet-tables))))
2344 ;; HACK! the snippet table created here is actually registered!
2346 (unless (or table (gethash major-mode yas/tables))
2347 (push (yas/table-get-create major-mode)
2350 (mapcar #'(lambda (table)
2352 (mapcar #'(lambda (subdir)
2353 (concat main-dir "/" subdir))
2354 (yas/guess-snippet-directories-1 table))))
2357 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2358 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2359 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2360 (let ((candidate (first (cdr table-and-dirs))))
2361 (unless (file-writable-p (file-name-directory candidate))
2362 (error (yas/format "%s is not writable." candidate)))
2363 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2365 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2369 (or main-table-string
2371 (yas/table-name (car table-and-dirs))))
2373 (make-directory candidate 'also-make-parents)
2374 ;; create the .yas-parents file here...
2377 (defun yas/new-snippet (&optional no-template)
2378 "Pops a new buffer for writing a snippet.
2380 Expands a snippet-writing snippet, unless the optional prefix arg
2381 NO-TEMPLATE is non-nil."
2383 (let ((guessed-directories (yas/guess-snippet-directories)))
2385 (switch-to-buffer "*new snippet*")
2387 (kill-all-local-variables)
2390 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2391 (intern (yas/table-name (car d))))
2392 guessed-directories))
2393 (unless no-template (yas/expand-snippet "\
2394 # -*- mode: snippet -*-
2396 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas/text)}}${3:
2397 # binding: ${4:direct-keybinding}}${5:
2398 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2403 (defun yas/compute-major-mode-and-parents (file)
2404 "Given FILE, find the nearest snippet directory for a given
2405 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2406 representing one or more of the mode's parents.
2408 Note that MODE-SYM need not be the symbol of a real major mode,
2409 neither do the elements of PARENTS."
2410 (let* ((file-dir (and file
2411 (directory-file-name (or (some #'(lambda (special)
2412 (locate-dominating-file file special))
2416 (directory-file-name (file-name-directory file))))))
2417 (parents-file-name (concat file-dir "/.yas-parents"))
2418 (major-mode-name (and file-dir
2419 (file-name-nondirectory file-dir)))
2420 (major-mode-sym (or (and major-mode-name
2421 (intern major-mode-name))))
2422 (parents (when (file-readable-p parents-file-name)
2426 (insert-file-contents parents-file-name)
2427 (buffer-substring-no-properties (point-min)
2429 (when major-mode-sym
2430 (cons major-mode-sym parents))))
2432 (defvar yas/editing-template nil
2433 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2435 (defvar yas/current-template nil
2436 "Holds the current template being expanded into a snippet.")
2438 (defvar yas/guessed-modes nil
2439 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2441 (defun yas/load-snippet-buffer (&optional kill)
2442 "Parse and load current buffer's snippet definition.
2444 With optional prefix argument KILL quit the window and buffer."
2447 ;; We have `yas/editing-template', this buffer's
2448 ;; content comes from a template which is already loaded and
2449 ;; neatly positioned,...
2451 (yas/editing-template
2452 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2453 (yas/template-table yas/editing-template)))
2454 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2455 ;; value from `yas/compute-major-mode-and-parents'
2458 (unless yas/guessed-modes
2459 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2460 (let* ((prompt (if (and (featurep 'ido)
2462 'ido-completing-read 'completing-read))
2463 (table (yas/table-get-create
2465 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2466 (if yas/guessed-modes
2467 (first yas/guessed-modes)
2469 (mapcar #'symbol-name yas/guessed-modes)
2474 (if (first yas/guessed-modes)
2475 (symbol-name (first yas/guessed-modes))))))))
2476 (set (make-local-variable 'yas/editing-template)
2477 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2479 ;; Now, offer to save this shit iff:
2481 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2482 ;; match this template's file (i.e. this is a library snippet, not
2483 ;; a user snippet) OR
2485 ;; 2) yas/editing-template comes from a file that we cannot write to...
2487 (when (or (not (yas/template-file yas/editing-template))
2488 (not (file-writable-p (yas/template-file yas/editing-template)))
2489 (and (listp yas/snippet-dirs)
2490 (second yas/snippet-dirs)
2491 (not (string-match (expand-file-name (first yas/snippet-dirs))
2492 (yas/template-file yas/editing-template)))))
2494 (when (y-or-n-p (yas/format "Looks like a library or new snippet. Save to new file? "))
2495 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2497 (yas/make-directory-maybe option))))
2499 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2500 (file-name-nondirectory (yas/template-file yas/editing-template)))
2501 (yas/template-name yas/editing-template))))
2502 (write-file (concat chosen "/"
2503 (read-from-minibuffer (format "File name to create in %s? " chosen)
2504 default-file-name)))
2505 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2508 (yas/message 3 "Snippet \"%s\" loaded for %s."
2509 (yas/template-name yas/editing-template)
2510 (yas/table-name (yas/template-table yas/editing-template))))
2513 (defun yas/tryout-snippet (&optional debug)
2514 "Test current buffers's snippet template in other buffer."
2516 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2517 (parsed (yas/parse-template))
2518 (test-mode (or (and (car major-mode-and-parent)
2519 (fboundp (car major-mode-and-parent))
2520 (car major-mode-and-parent))
2521 (first yas/guessed-modes)
2522 (intern (read-from-minibuffer (yas/format "Please input a mode: ")))))
2523 (yas/current-template
2526 (yas/populate-template (yas/make-blank-template)
2527 :table nil ;; no tables for ephemeral snippets
2529 :content (second parsed)
2530 :name (third parsed)
2531 :expand-env (sixth parsed)))))
2532 (cond (yas/current-template
2533 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2534 (kill-buffer (get-buffer-create buffer-name))
2535 (switch-to-buffer (get-buffer-create buffer-name))
2536 (setq buffer-undo-list nil)
2537 (condition-case nil (funcall test-mode) (error nil))
2538 (setq buffer-read-only nil)
2539 (yas/expand-snippet (yas/template-content yas/current-template)
2542 (yas/template-expand-env yas/current-template))
2544 (require 'yasnippet-debug nil t))
2545 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2547 (yas/message 3 "Cannot test snippet for unknown major mode")))))
2549 (defun yas/template-fine-group (template)
2550 (car (last (or (yas/template-group template)
2551 (yas/template-perm-group template)))))
2553 (defun yas/describe-tables (&optional choose)
2554 "Display snippets for each table."
2556 (let* ((by-name-hash (and choose
2557 (y-or-n-p "Show by namehash? ")))
2558 (buffer (get-buffer-create "*YASnippet tables*"))
2559 (active-tables (yas/get-snippet-tables))
2560 (remain-tables (let ((all))
2561 (maphash #'(lambda (k v)
2562 (unless (find v active-tables)
2566 (table-lists (list active-tables remain-tables))
2567 (original-buffer (current-buffer))
2569 (yas/condition-cache-timestamp (current-time)))
2570 (with-current-buffer buffer
2571 (setq buffer-read-only nil)
2573 (cond ((not by-name-hash)
2574 (insert "YASnippet tables: \n")
2575 (while (and table-lists
2577 (dolist (table (car table-lists))
2578 (yas/describe-pretty-table table original-buffer))
2579 (setq table-lists (cdr table-lists))
2581 (yas/create-snippet-xrefs)
2582 (display-buffer buffer)
2583 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2584 (yas/create-snippet-xrefs)
2588 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2589 (dolist (table (append active-tables remain-tables))
2590 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2592 (maphash #'(lambda (k v)
2594 (yas/table-hash table))
2596 (insert (format " key %s maps snippets: %s\n" key
2598 (maphash #'(lambda (k v)
2600 (gethash key (yas/table-hash table)))
2603 (setq buffer-read-only t))
2604 (display-buffer buffer)))
2606 (defun yas/describe-pretty-table (table &optional original-buffer)
2607 (insert (format "\nSnippet table `%s'"
2608 (yas/table-name table)))
2609 (if (yas/table-parents table)
2610 (insert (format " parents: %s\n"
2611 (mapcar #'yas/table-name
2612 (yas/table-parents table))))
2614 (insert (make-string 100 ?-) "\n")
2615 (insert "group state name key binding\n")
2616 (let ((groups-hash (make-hash-table :test #'equal)))
2617 (maphash #'(lambda (k v)
2618 (let ((group (or (yas/template-fine-group v)
2620 (when (yas/template-name v)
2622 (cons v (gethash group groups-hash))
2624 (yas/table-uuidhash table))
2626 #'(lambda (group templates)
2627 (setq group (truncate-string-to-width group 25 0 ? "..."))
2628 (insert (make-string 100 ?-) "\n")
2629 (dolist (p templates)
2630 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2634 (setq group (make-string (length group) ? ))))
2635 (condition-string (let ((condition (yas/template-condition p)))
2638 (with-current-buffer original-buffer
2639 (if (yas/eval-condition condition)
2644 (insert condition-string " ")
2646 (if (string-match "\\.\\.\\.$" name)
2650 (insert (truncate-string-to-width (or (yas/template-key p) "")
2652 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2659 ;;; User convenience functions, for using in snippet definitions
2661 (defvar yas/modified-p nil
2662 "Non-nil if field has been modified by user or transformation.")
2664 (defvar yas/moving-away-p nil
2665 "Non-nil if user is about to exit field.")
2667 (defvar yas/text nil
2668 "Contains current field text.")
2670 (defun yas/substr (str pattern &optional subexp)
2671 "Search PATTERN in STR and return SUBEXPth match.
2673 If found, the content of subexp group SUBEXP (default 0) is
2674 returned, or else the original STR will be returned."
2675 (let ((grp (or subexp 0)))
2677 (if (string-match pattern str)
2678 (match-string-no-properties grp str)
2681 (defun yas/choose-value (possibilities)
2682 "Prompt for a string in the list POSSIBILITIES and return it."
2683 (unless (or yas/moving-away-p
2685 (some #'(lambda (fn)
2686 (funcall fn "Choose: " possibilities))
2687 yas/prompt-functions)))
2689 (defun yas/key-to-value (alist)
2690 "Prompt for a string in the list POSSIBILITIES and return it."
2691 (unless (or yas/moving-away-p
2693 (let ((key (read-key-sequence "")))
2695 (or (cdr (find key alist :key #'car :test #'string=))
2698 (defun yas/throw (text)
2699 "Throw a yas/exception with TEXT as the reason."
2700 (throw 'yas/exception (cons 'yas/exception text)))
2702 (defun yas/verify-value (possibilities)
2703 "Verify that the current field value is in POSSIBILITIES
2705 Otherwise throw exception."
2706 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2707 (yas/throw (yas/format "Field only allows %s" possibilities))))
2709 (defun yas/field-value (number)
2710 "Get the string for field with NUMBER.
2712 Use this in primary and mirror transformations to tget."
2713 (let* ((snippet (car (yas/snippets-at-point)))
2715 (yas/snippet-find-field snippet number))))
2717 (yas/field-text-for-display field))))
2720 "Return `yas/text' if that exists and is non-empty, else nil."
2722 (not (string= "" yas/text)))
2725 ;; (defun yas/selected-text ()
2726 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2727 ;; (if (and yas/selected-text
2728 ;; (not (string= "" yas/selected-text)))
2729 ;; yas/selected-text))
2731 (defun yas/get-field-once (number &optional transform-fn)
2732 (unless yas/modified-p
2734 (funcall transform-fn (yas/field-value number))
2735 (yas/field-value number))))
2737 (defun yas/default-from-field (number)
2738 (unless yas/modified-p
2739 (yas/field-value number)))
2741 (defun yas/inside-string ()
2742 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2744 (defun yas/unimplemented (&optional missing-feature)
2745 (if yas/current-template
2746 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2749 (yas/visit-snippet-file-1 yas/current-template))
2750 (message "No implementation. Missing %s" (or missing-feature "something"))))
2753 ;;; Snippet expansion and field management
2755 (defvar yas/active-field-overlay nil
2756 "Overlays the currently active field.")
2758 (defvar yas/field-protection-overlays nil
2759 "Two overlays protect the current active field ")
2761 (defconst yas/prefix nil
2762 "A prefix argument for expansion direct from keybindings")
2764 (defvar yas/selected-text nil
2765 "The selected region deleted on the last snippet expansion.")
2767 (defvar yas/start-column nil
2768 "The column where the snippet expansion started.")
2770 (make-variable-buffer-local 'yas/active-field-overlay)
2771 (make-variable-buffer-local 'yas/field-protection-overlays)
2772 (put 'yas/active-field-overlay 'permanent-local t)
2773 (put 'yas/field-protection-overlays 'permanent-local t)
2775 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2781 (id (yas/snippet-next-id) :read-only t)
2782 (control-overlay nil)
2784 ;; stacked expansion: the `previous-active-field' slot saves the
2785 ;; active field where the child expansion took place
2786 previous-active-field
2789 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2799 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2806 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2810 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2811 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2813 If there is no transform for ht field, return nil.
2815 If there is a transform but it returns nil, return the empty
2816 string iff EMPTY-ON-NIL-P is true."
2817 (let* ((yas/text (yas/field-text-for-display field))
2819 (yas/modified-p (yas/field-modified-p field))
2820 (yas/moving-away-p nil)
2821 (transform (if (yas/mirror-p field-or-mirror)
2822 (yas/mirror-transform field-or-mirror)
2823 (yas/field-transform field-or-mirror)))
2824 (start-point (if (yas/mirror-p field-or-mirror)
2825 (yas/mirror-start field-or-mirror)
2826 (yas/field-start field-or-mirror)))
2827 (transformed (and transform
2829 (goto-char start-point)
2830 (let ((ret (yas/eval-lisp transform)))
2831 (or ret (and empty-on-nil-p "")))))))
2834 (defsubst yas/replace-all (from to &optional text)
2835 "Replace all occurance from FROM to TO.
2837 With optional string TEXT do it in that string."
2839 (replace-regexp-in-string (regexp-quote from) to text t t)
2840 (goto-char (point-min))
2841 (while (search-forward from nil t)
2842 (replace-match to t t text))))
2844 (defun yas/snippet-find-field (snippet number)
2845 (find-if #'(lambda (field)
2846 (eq number (yas/field-number field)))
2847 (yas/snippet-fields snippet)))
2849 (defun yas/snippet-sort-fields (snippet)
2850 "Sort the fields of SNIPPET in navigation order."
2851 (setf (yas/snippet-fields snippet)
2852 (sort (yas/snippet-fields snippet)
2853 #'yas/snippet-field-compare)))
2855 (defun yas/snippet-field-compare (field1 field2)
2856 "Compare two fields. The field with a number is sorted first.
2857 If they both have a number, compare through the number. If neither
2858 have, compare through the field's start point"
2859 (let ((n1 (yas/field-number field1))
2860 (n2 (yas/field-number field2)))
2863 (or (zerop n2) (and (not (zerop n1))
2868 (< (yas/field-start field1)
2869 (yas/field-start field2))))))
2871 (defun yas/field-probably-deleted-p (snippet field)
2872 "Guess if SNIPPET's FIELD should be skipped."
2874 ;; field must be zero lentgh
2876 (zerop (- (yas/field-start field) (yas/field-end field)))
2879 ;; 1) is a nested field and it's been modified
2881 (and (yas/field-parent-field field)
2882 (yas/field-modified-p field))
2883 ;; 2) ends just before the snippet end
2885 (and (eq field (car (last (yas/snippet-fields snippet))))
2886 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2887 ;; the field numbered 0, just before the exit marker, should
2890 (not (zerop (yas/field-number field)))))
2892 (defun yas/snippets-at-point (&optional all-snippets)
2893 "Return a sorted list of snippets at point, most recently
2896 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2897 (overlay-get ov 'yas/snippet))
2899 (overlays-in (point-min) (point-max))
2900 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2902 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2904 (defun yas/next-field-or-maybe-expand ()
2905 "Try to expand a snippet at a key before point, otherwise
2906 delegate to `yas/next-field'."
2908 (if yas/triggers-in-field
2909 (let ((yas/fallback-behavior 'return-nil)
2910 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2912 (unless (yas/expand-from-trigger-key active-field)
2916 (defun yas/next-field (&optional arg)
2917 "Navigate to next field. If there's none, exit the snippet."
2921 (snippet (first (yas/snippets-at-point)))
2922 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2923 (live-fields (remove-if #'(lambda (field)
2924 (and (not (eq field active-field))
2925 (yas/field-probably-deleted-p snippet field)))
2926 (yas/snippet-fields snippet)))
2927 (active-field-pos (position active-field live-fields))
2928 (target-pos (and active-field-pos (+ arg active-field-pos)))
2929 (target-field (and target-pos (nth target-pos live-fields))))
2930 ;; First check if we're moving out of a field with a transform
2932 (when (and active-field
2933 (yas/field-transform active-field))
2934 (let* ((yas/moving-away-p t)
2935 (yas/text (yas/field-text-for-display active-field))
2937 (yas/modified-p (yas/field-modified-p active-field)))
2938 ;; primary field transform: exit call to field-transform
2939 (yas/eval-lisp (yas/field-transform active-field))))
2940 ;; Now actually move...
2941 (cond ((and target-pos (>= target-pos (length live-fields)))
2942 (yas/exit-snippet snippet))
2944 (yas/move-to-field snippet target-field))
2948 (defun yas/place-overlays (snippet field)
2949 "Correctly place overlays for SNIPPET's FIELD"
2950 (yas/make-move-field-protection-overlays snippet field)
2951 (yas/make-move-active-field-overlay snippet field))
2953 (defun yas/move-to-field (snippet field)
2954 "Update SNIPPET to move to field FIELD.
2956 Also create some protection overlays"
2957 (goto-char (yas/field-start field))
2958 (yas/place-overlays snippet field)
2959 (overlay-put yas/active-field-overlay 'yas/field field)
2960 (let ((number (yas/field-number field)))
2961 ;; check for the special ${0: ...} field
2962 (if (and number (zerop number))
2964 (set-mark (yas/field-end field))
2965 (setf (yas/snippet-force-exit snippet)
2966 (or (yas/field-transform field)
2968 ;; make this field active
2969 (setf (yas/snippet-active-field snippet) field)
2970 ;; primary field transform: first call to snippet transform
2971 (unless (yas/field-modified-p field)
2972 (if (yas/field-update-display field snippet)
2973 (yas/update-mirrors snippet)
2974 (setf (yas/field-modified-p field) nil))))))
2976 (defun yas/prev-field ()
2977 "Navigate to prev field. If there's none, exit the snippet."
2979 (yas/next-field -1))
2981 (defun yas/abort-snippet (&optional snippet)
2983 (let ((snippet (or snippet
2984 (car (yas/snippets-at-point)))))
2986 (setf (yas/snippet-force-exit snippet) t))))
2988 (defun yas/exit-snippet (snippet)
2989 "Goto exit-marker of SNIPPET."
2990 (interactive (list (first (yas/snippets-at-point))))
2992 (setf (yas/snippet-force-exit snippet) t)
2993 (goto-char (if (yas/snippet-exit snippet)
2994 (yas/exit-marker (yas/snippet-exit snippet))
2995 (overlay-end (yas/snippet-control-overlay snippet))))))
2997 (defun yas/exit-all-snippets ()
2998 "Exit all snippets."
3000 (mapc #'(lambda (snippet)
3001 (yas/exit-snippet snippet)
3002 (yas/check-commit-snippet))
3003 (yas/snippets-at-point 'all-snippets)))
3006 ;;; Some low level snippet-routines
3008 (defmacro yas/inhibit-overlay-hooks (&rest body)
3009 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
3010 (declare (indent 0))
3011 `(let ((yas/inhibit-overlay-hooks t))
3014 (defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
3015 (defvar yas/snippet-end nil "End position of the last snippet commited.")
3017 (defun yas/commit-snippet (snippet)
3018 "Commit SNIPPET, but leave point as it is. This renders the
3019 snippet as ordinary text."
3021 (let ((control-overlay (yas/snippet-control-overlay snippet)))
3023 ;; Save the end of the moribund snippet in case we need to revive it
3024 ;; its original expansion.
3026 (when (and control-overlay
3027 (overlay-buffer control-overlay))
3028 (setq yas/snippet-beg (overlay-start control-overlay))
3029 (setq yas/snippet-end (overlay-end control-overlay))
3030 (delete-overlay control-overlay))
3032 (yas/inhibit-overlay-hooks
3033 (when yas/active-field-overlay
3034 (delete-overlay yas/active-field-overlay))
3035 (when yas/field-protection-overlays
3036 (mapc #'delete-overlay yas/field-protection-overlays)))
3038 ;; stacked expansion: if the original expansion took place from a
3039 ;; field, make sure we advance it here at least to
3040 ;; `yas/snippet-end'...
3042 (let ((previous-field (yas/snippet-previous-active-field snippet)))
3043 (when (and yas/snippet-end previous-field)
3044 (yas/advance-end-maybe previous-field yas/snippet-end)))
3046 ;; Convert all markers to points,
3048 (yas/markers-to-points snippet)
3050 ;; Take care of snippet revival
3052 (if yas/snippet-revival
3053 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
3055 ;; Dismember the snippet... this is useful if we get called
3056 ;; again from `yas/take-care-of-redo'....
3057 (setf (yas/snippet-fields snippet) nil)))
3059 (yas/message 3 "Snippet %s exited." (yas/snippet-id snippet)))
3061 (defun yas/safely-run-hooks (hook-var)
3062 (condition-case error
3063 (run-hooks hook-var)
3065 (yas/message 3 "%s error: %s" hook-var (error-message-string error)))))
3068 (defun yas/check-commit-snippet ()
3069 "Checks if point exited the currently active field of the
3070 snippet, if so cleans up the whole snippet up."
3071 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3072 (snippets-left snippets)
3073 (snippet-exit-transform))
3074 (dolist (snippet snippets)
3075 (let ((active-field (yas/snippet-active-field snippet)))
3076 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3077 (cond ((or snippet-exit-transform
3078 (not (and active-field (yas/field-contains-point-p active-field))))
3079 (setq snippets-left (delete snippet snippets-left))
3080 (setf (yas/snippet-force-exit snippet) nil)
3081 (yas/commit-snippet snippet))
3083 (or (not yas/active-field-overlay)
3084 (not (overlay-buffer yas/active-field-overlay))))
3086 ;; stacked expansion: this case is mainly for recent
3087 ;; snippet exits that place us back int the field of
3091 (yas/move-to-field snippet active-field)
3092 (yas/update-mirrors snippet)))
3095 (unless (or (null snippets) snippets-left)
3096 (if snippet-exit-transform
3097 (yas/eval-lisp-no-saves snippet-exit-transform))
3098 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3100 ;; Apropos markers-to-points:
3102 ;; This was found useful for performance reasons, so that an
3103 ;; excessive number of live markers aren't kept around in the
3104 ;; `buffer-undo-list'. However, in `markers-to-points', the
3105 ;; set-to-nil markers can't simply be discarded and replaced with
3106 ;; fresh ones in `points-to-markers'. The original marker that was
3107 ;; just set to nil has to be reused.
3109 ;; This shouldn't bring horrible problems with undo/redo, but it
3112 (defun yas/markers-to-points (snippet)
3113 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3114 where POINT is the original position of the marker and MARKER is
3115 the original marker object with the position set to nil."
3116 (dolist (field (yas/snippet-fields snippet))
3117 (let ((start (marker-position (yas/field-start field)))
3118 (end (marker-position (yas/field-end field))))
3119 (set-marker (yas/field-start field) nil)
3120 (set-marker (yas/field-end field) nil)
3121 (setf (yas/field-start field) (cons start (yas/field-start field)))
3122 (setf (yas/field-end field) (cons end (yas/field-end field))))
3123 (dolist (mirror (yas/field-mirrors field))
3124 (let ((start (marker-position (yas/mirror-start mirror)))
3125 (end (marker-position (yas/mirror-end mirror))))
3126 (set-marker (yas/mirror-start mirror) nil)
3127 (set-marker (yas/mirror-end mirror) nil)
3128 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3129 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3130 (let ((snippet-exit (yas/snippet-exit snippet)))
3132 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3133 (set-marker (yas/exit-marker snippet-exit) nil)
3134 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3136 (defun yas/points-to-markers (snippet)
3137 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3138 is done by setting MARKER to POINT with `set-marker'."
3139 (dolist (field (yas/snippet-fields snippet))
3140 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3141 (car (yas/field-start field))))
3142 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3143 (car (yas/field-end field))))
3144 (dolist (mirror (yas/field-mirrors field))
3145 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3146 (car (yas/mirror-start mirror))))
3147 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3148 (car (yas/mirror-end mirror))))))
3149 (let ((snippet-exit (yas/snippet-exit snippet)))
3151 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3152 (car (yas/exit-marker snippet-exit)))))))
3154 (defun yas/field-contains-point-p (field &optional point)
3155 (let ((point (or point
3157 (and (>= point (yas/field-start field))
3158 (<= point (yas/field-end field)))))
3160 (defun yas/field-text-for-display (field)
3161 "Return the propertized display text for field FIELD. "
3162 (buffer-substring (yas/field-start field) (yas/field-end field)))
3164 (defun yas/undo-in-progress ()
3165 "True if some kind of undo is in progress"
3166 (or undo-in-progress
3167 (eq this-command 'undo)
3168 (eq this-command 'redo)))
3170 (defun yas/make-control-overlay (snippet start end)
3171 "Creates the control overlay that surrounds the snippet and
3173 (let ((overlay (make-overlay start
3178 (overlay-put overlay 'keymap yas/keymap)
3179 (overlay-put overlay 'priority 100)
3180 (overlay-put overlay 'yas/snippet snippet)
3183 (defun yas/skip-and-clear-or-delete-char (&optional field)
3184 "Clears unmodified field if at field start, skips to next tab.
3186 Otherwise deletes a character normally by calling `delete-char'."
3188 (let ((field (or field
3189 (and yas/active-field-overlay
3190 (overlay-buffer yas/active-field-overlay)
3191 (overlay-get yas/active-field-overlay 'yas/field)))))
3193 (not (yas/field-modified-p field))
3194 (eq (point) (marker-position (yas/field-start field))))
3195 (yas/skip-and-clear field)
3198 (call-interactively 'delete-char)))))
3200 (defun yas/skip-and-clear (field)
3201 "Deletes the region of FIELD and sets it modified state to t"
3202 ;; Just before skipping-and-clearing the field, mark its children
3203 ;; fields as modified, too. If the childen have mirrors-in-fields
3204 ;; this prevents them from updating erroneously (we're skipping and
3207 (yas/mark-this-and-children-modified field)
3208 (delete-region (yas/field-start field) (yas/field-end field)))
3210 (defun yas/mark-this-and-children-modified (field)
3211 (setf (yas/field-modified-p field) t)
3212 (let ((fom (yas/field-next field)))
3214 (yas/fom-parent-field fom))
3215 (when (and (eq (yas/fom-parent-field fom) field)
3217 (yas/mark-this-and-children-modified fom))
3218 (setq fom (yas/fom-next fom)))))
3220 (defun yas/make-move-active-field-overlay (snippet field)
3221 "Place the active field overlay in SNIPPET's FIELD.
3223 Move the overlay, or create it if it does not exit."
3224 (if (and yas/active-field-overlay
3225 (overlay-buffer yas/active-field-overlay))
3226 (move-overlay yas/active-field-overlay
3227 (yas/field-start field)
3228 (yas/field-end field))
3229 (setq yas/active-field-overlay
3230 (make-overlay (yas/field-start field)
3231 (yas/field-end field)
3233 (overlay-put yas/active-field-overlay 'priority 100)
3234 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3235 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3236 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3237 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3238 '(yas/on-field-overlay-modification))
3239 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3240 '(yas/on-field-overlay-modification))))
3242 (defvar yas/inhibit-overlay-hooks nil
3243 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3245 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3246 "Clears the field and updates mirrors, conditionally.
3248 Only clears the field if it hasn't been modified and it point it
3249 at field start. This hook doesn't do anything if an undo is in
3251 (unless (or yas/inhibit-overlay-hooks
3252 (yas/undo-in-progress))
3253 (let* ((field (overlay-get overlay 'yas/field))
3254 (number (and field (yas/field-number field)))
3255 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3257 (yas/advance-end-maybe field (overlay-end overlay))
3259 (yas/field-update-display field snippet))
3260 (yas/update-mirrors snippet))
3262 (when (and (not after?)
3263 (not (yas/field-modified-p field))
3264 (eq (point) (if (markerp (yas/field-start field))
3265 (marker-position (yas/field-start field))
3266 (yas/field-start field))))
3267 (yas/skip-and-clear field))
3268 (setf (yas/field-modified-p field) t))))))
3270 ;;; Apropos protection overlays:
3272 ;; These exist for nasty users who will try to delete parts of the
3273 ;; snippet outside the active field. Actual protection happens in
3274 ;; `yas/on-protection-overlay-modification'.
3276 ;; Currently this signals an error which inhibits the command. For
3277 ;; commands that move point (like `kill-line'), point is restored in
3278 ;; the `yas/post-command-handler' using a global
3279 ;; `yas/protection-violation' variable.
3281 ;; Alternatively, I've experimented with an implementation that
3282 ;; commits the snippet before actually calling `this-command'
3283 ;; interactively, and then signals an eror, which is ignored. but
3284 ;; blocks all other million modification hooks. This presented some
3285 ;; problems with stacked expansion.
3288 (defun yas/make-move-field-protection-overlays (snippet field)
3289 "Place protection overlays surrounding SNIPPET's FIELD.
3291 Move the overlays, or create them if they do not exit."
3292 (let ((start (yas/field-start field))
3293 (end (yas/field-end field)))
3294 ;; First check if the (1+ end) is contained in the buffer,
3295 ;; otherwise we'll have to do a bit of cheating and silently
3296 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3297 ;; when using stacked expansion
3299 (when (< (buffer-size) end)
3301 (yas/inhibit-overlay-hooks
3302 (goto-char (point-max))
3304 ;; go on to normal overlay creation/moving
3306 (cond ((and yas/field-protection-overlays
3307 (every #'overlay-buffer yas/field-protection-overlays))
3308 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3309 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3311 (setq yas/field-protection-overlays
3312 (list (make-overlay (1- start) start nil t nil)
3313 (make-overlay end (1+ end) nil t nil)))
3314 (dolist (ov yas/field-protection-overlays)
3315 (overlay-put ov 'face 'yas/field-debug-face)
3316 (overlay-put ov 'yas/snippet snippet)
3317 ;; (overlay-put ov 'evaporate t)
3318 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3320 (defvar yas/protection-violation nil
3321 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3323 Functions in the `post-command-hook', for example
3324 `yas/post-command-handler' can check it and reset its value to
3325 nil. The variables value is the point where the violation
3328 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3329 "Signals a snippet violation, then issues error.
3331 The error should be ignored in `debug-ignored-errors'"
3332 (unless yas/inhibit-overlay-hooks
3333 (cond ((not (or after?
3334 (yas/undo-in-progress)))
3335 (setq yas/protection-violation (point))
3336 (error "Exit the snippet first!")))))
3338 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3341 ;;; Apropos stacked expansion:
3343 ;; the parent snippet does not run its fields modification hooks
3344 ;; (`yas/on-field-overlay-modification' and
3345 ;; `yas/on-protection-overlay-modification') while the child snippet
3346 ;; is active. This means, among other things, that the mirrors of the
3347 ;; parent snippet are not updated, this only happening when one exits
3348 ;; the child snippet.
3350 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3351 ;; bits of code in `yas/expand-snippet' and
3352 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3355 ;; This was thought to be safer in in an undo/redo perpective, but
3356 ;; maybe the correct implementation is to make the globals
3357 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3358 ;; snippet-local and be active even while the child snippet is
3359 ;; running. This would mean a lot of overlay modification hooks
3360 ;; running, but if managed correctly (including overlay priorities)
3361 ;; they should account for all situations...
3364 (defun yas/expand-snippet (content &optional start end expand-env)
3365 "Expand snippet CONTENT at current point.
3367 Text between START and END will be deleted before inserting
3368 template. EXPAND-ENV is are let-style variable to value bindings
3369 considered when expanding the snippet."
3370 (run-hooks 'yas/before-expand-snippet-hook)
3372 ;; If a region is active, set `yas/selected-text'
3373 (setq yas/selected-text
3374 (when (region-active-p)
3375 (prog1 (buffer-substring-no-properties (region-beginning)
3377 (unless start (setq start (region-beginning))
3378 (unless end (setq end (region-end)))))))
3384 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3385 (start (or start (point)))
3386 (end (or end (point)))
3388 (setq yas/indent-original-column (current-column))
3389 ;; Delete the region to delete, this *does* get undo-recorded.
3391 (when (and to-delete
3393 (delete-region start end))
3395 (cond ((listp content)
3396 ;; x) This is a snippet-command
3398 (yas/eval-lisp-no-saves content))
3400 ;; x) This is a snippet-snippet :-)
3402 ;; Narrow the region down to the content, shoosh the
3403 ;; `buffer-undo-list', and create the snippet, the new
3404 ;; snippet updates its mirrors once, so we are left with
3405 ;; some plain text. The undo action for deleting this
3406 ;; plain text will get recorded at the end.
3408 ;; stacked expansion: also shoosh the overlay modification hooks
3410 (narrow-to-region start start)
3411 (let ((buffer-undo-list t))
3412 ;; snippet creation might evaluate users elisp, which
3413 ;; might generate errors, so we have to be ready to catch
3414 ;; them mostly to make the undo information
3416 (setq yas/start-column (save-restriction (widen) (current-column)))
3417 (yas/inhibit-overlay-hooks
3420 (eval `(let* ,expand-env
3422 (yas/snippet-create (point-min) (point-max))))
3424 (yas/snippet-create (point-min) (point-max)))))))
3426 ;; stacked-expansion: This checks for stacked expansion, save the
3427 ;; `yas/previous-active-field' and advance its boudary.
3429 (let ((existing-field (and yas/active-field-overlay
3430 (overlay-buffer yas/active-field-overlay)
3431 (overlay-get yas/active-field-overlay 'yas/field))))
3432 (when existing-field
3433 (setf (yas/snippet-previous-active-field snippet) existing-field)
3434 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3436 ;; Exit the snippet immediately if no fields
3438 (unless (yas/snippet-fields snippet)
3439 (yas/exit-snippet snippet))
3441 ;; Push two undo actions: the deletion of the inserted contents of
3442 ;; the new snippet (without the "key") followed by an apply of
3443 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3445 ;; A small exception, if `yas/also-auto-indent-first-line'
3446 ;; is t and `yas/indent' decides to indent the line to a
3447 ;; point before the actual expansion point, undo would be
3448 ;; messed up. We call the early point "newstart"". case,
3449 ;; and attempt to fix undo.
3451 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3452 (end (overlay-end (yas/snippet-control-overlay snippet))))
3453 (when (< newstart start)
3454 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3455 (push (cons newstart end) buffer-undo-list)
3456 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3458 ;; Now, schedule a move to the first field
3460 (let ((first-field (car (yas/snippet-fields snippet))))
3462 (sit-for 0) ;; fix issue 125
3463 (yas/move-to-field snippet first-field)))
3464 (yas/message 3 "snippet expanded.")
3467 (defun yas/take-care-of-redo (beg end snippet)
3468 "Commits SNIPPET, which in turn pushes an undo action for
3471 Meant to exit in the `buffer-undo-list'."
3472 ;; slightly optimize: this action is only needed for snippets with
3473 ;; at least one field
3474 (when (yas/snippet-fields snippet)
3475 (yas/commit-snippet snippet)))
3477 (defun yas/snippet-revive (beg end snippet)
3478 "Revives the SNIPPET and creates a control overlay from BEG to
3481 BEG and END are, we hope, the original snippets boudaries. All
3482 the markers/points exiting existing inside SNIPPET should point
3483 to their correct locations *at the time the snippet is revived*.
3485 After revival, push the `yas/take-care-of-redo' in the
3487 ;; Reconvert all the points to markers
3489 (yas/points-to-markers snippet)
3490 ;; When at least one editable field existed in the zombie snippet,
3491 ;; try to revive the whole thing...
3493 (let ((target-field (or (yas/snippet-active-field snippet)
3494 (car (yas/snippet-fields snippet)))))
3496 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3497 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3499 (yas/move-to-field snippet target-field)
3501 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3502 buffer-undo-list))))
3504 (defun yas/snippet-create (begin end)
3505 "Creates a snippet from an template inserted between BEGIN and END.
3507 Returns the newly created snippet."
3508 (let ((snippet (yas/make-snippet)))
3510 (yas/snippet-parse-create snippet)
3512 ;; Sort and link each field
3513 (yas/snippet-sort-fields snippet)
3515 ;; Create keymap overlay for snippet
3516 (setf (yas/snippet-control-overlay snippet)
3517 (yas/make-control-overlay snippet (point-min) (point-max)))
3520 (goto-char (point-max))
3525 ;;; Apropos adjacencies and "fom's":
3527 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3528 ;; recently expanded snippet, we might actually have many fields,
3529 ;; mirrors (and the snippet exit) in the very same position in the
3530 ;; buffer. Therefore we need to single-link the
3531 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3532 ;; their original positions in the buffer.
3534 ;; Then we have operation `yas/advance-end-maybe' and
3535 ;; `yas/advance-start-maybe', which conditionally push the starts and
3536 ;; ends of these foms down the chain.
3538 ;; This allows for like the printf with the magic ",":
3540 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3541 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3543 (defun yas/fom-start (fom)
3544 (cond ((yas/field-p fom)
3545 (yas/field-start fom))
3547 (yas/mirror-start fom))
3549 (yas/exit-marker fom))))
3551 (defun yas/fom-end (fom)
3552 (cond ((yas/field-p fom)
3553 (yas/field-end fom))
3555 (yas/mirror-end fom))
3557 (yas/exit-marker fom))))
3559 (defun yas/fom-next (fom)
3560 (cond ((yas/field-p fom)
3561 (yas/field-next fom))
3563 (yas/mirror-next fom))
3565 (yas/exit-next fom))))
3567 (defun yas/fom-parent-field (fom)
3568 (cond ((yas/field-p fom)
3569 (yas/field-parent-field fom))
3571 (yas/mirror-parent-field fom))
3575 (defun yas/calculate-adjacencies (snippet)
3576 "Calculate adjacencies for fields or mirrors of SNIPPET.
3578 This is according to their relative positions in the buffer, and
3579 has to be called before the $-constructs are deleted."
3580 (flet ((yas/fom-set-next-fom (fom nextfom)
3581 (cond ((yas/field-p fom)
3582 (setf (yas/field-next fom) nextfom))
3584 (setf (yas/mirror-next fom) nextfom))
3586 (setf (yas/exit-next fom) nextfom))))
3587 (yas/compare-fom-begs (fom1 fom2)
3588 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3590 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3591 (yas/link-foms (fom1 fom2)
3592 (yas/fom-set-next-fom fom1 fom2)))
3593 ;; make some yas/field, yas/mirror and yas/exit soup
3595 (when (yas/snippet-exit snippet)
3596 (push (yas/snippet-exit snippet) soup))
3597 (dolist (field (yas/snippet-fields snippet))
3599 (dolist (mirror (yas/field-mirrors field))
3600 (push mirror soup)))
3603 #'yas/compare-fom-begs))
3605 (reduce #'yas/link-foms soup)))))
3607 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3608 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3610 Use the tighest containing field if more than one field contains
3611 the mirror. Intended to be called *before* the dollar-regions are
3613 (let ((min (point-min))
3615 (dolist (field (yas/snippet-fields snippet))
3616 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3617 (<= (yas/mirror-end mirror) (yas/field-end field))
3618 (< min (yas/field-start field))
3619 (< (yas/field-end field) max))
3620 (setq min (yas/field-start field)
3621 max (yas/field-end field))
3622 (setf (yas/mirror-parent-field mirror) field)))))
3624 (defun yas/advance-end-maybe (fom newend)
3625 "Maybe advance FOM's end to NEWEND if it needs it.
3629 * call `yas/advance-start-maybe' on FOM's next fom.
3631 * in case FOM is field call `yas/advance-end-maybe' on its parent
3634 Also, if FOM is an exit-marker, always call
3635 `yas/advance-start-maybe' on its next fom. This is beacuse
3636 exit-marker have identical start and end markers.
3639 (cond ((and fom (< (yas/fom-end fom) newend))
3640 (set-marker (yas/fom-end fom) newend)
3641 (yas/advance-start-maybe (yas/fom-next fom) newend)
3642 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3644 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3646 (defun yas/advance-start-maybe (fom newstart)
3647 "Maybe advance FOM's start to NEWSTART if it needs it.
3649 If it does, also call `yas/advance-end-maybe' on FOM."
3650 (when (and fom (< (yas/fom-start fom) newstart))
3651 (set-marker (yas/fom-start fom) newstart)
3652 (yas/advance-end-maybe fom newstart)))
3654 (defun yas/advance-end-of-parents-maybe (field newend)
3655 "Like `yas/advance-end-maybe' but for parent fields.
3657 Only works for fields and doesn't care about the start of the
3658 next FOM. Works its way up recursively for parents of parents."
3660 (< (yas/field-end field) newend))
3661 (set-marker (yas/field-end field) newend)
3662 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3664 (defvar yas/dollar-regions nil
3665 "When expanding the snippet the \"parse-create\" functions add
3666 cons cells to this var")
3668 (defun yas/snippet-parse-create (snippet)
3669 "Parse a recently inserted snippet template, creating all
3670 necessary fields, mirrors and exit points.
3672 Meant to be called in a narrowed buffer, does various passes"
3673 (let ((parse-start (point)))
3674 ;; Reset the yas/dollar-regions
3676 (setq yas/dollar-regions nil)
3677 ;; protect escaped quote, backquotes and backslashes
3679 (yas/protect-escapes nil `(?\\ ?` ?'))
3680 ;; replace all backquoted expressions
3682 (goto-char parse-start)
3683 (yas/replace-backquotes)
3684 ;; protect escapes again since previous steps might have generated
3685 ;; more characters needing escaping
3687 (goto-char parse-start)
3688 (yas/protect-escapes)
3689 ;; parse fields with {}
3691 (goto-char parse-start)
3692 (yas/field-parse-create snippet)
3693 ;; parse simple mirrors and fields
3695 (goto-char parse-start)
3696 (yas/simple-mirror-parse-create snippet)
3697 ;; parse mirror transforms
3699 (goto-char parse-start)
3700 (yas/transform-mirror-parse-create snippet)
3701 ;; calculate adjacencies of fields and mirrors
3703 (yas/calculate-adjacencies snippet)
3704 ;; Delete $-constructs
3706 (yas/delete-regions yas/dollar-regions)
3709 (goto-char parse-start)
3710 (yas/restore-escapes)
3711 ;; update mirrors for the first time
3713 (yas/update-mirrors snippet)
3714 ;; indent the best we can
3716 (goto-char parse-start)
3717 (yas/indent snippet)))
3719 (defun yas/indent-according-to-mode (snippet-markers)
3720 "Indent current line according to mode, preserving
3722 ;;; Apropos indenting problems....
3724 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3725 ;; is available. Some implementations of these functions delete text
3726 ;; before they insert. If there happens to be a marker just after
3727 ;; the text being deleted, the insertion actually happens after the
3728 ;; marker, which misplaces it.
3730 ;; This would also happen if we had used overlays with the
3731 ;; `front-advance' property set to nil.
3733 ;; This is why I have these `trouble-markers', they are the ones at
3734 ;; they are the ones at the first non-whitespace char at the line
3735 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3736 ;; we should be at the correct to restore them to. All other
3737 ;; non-trouble-markers have been *pushed* and don't need special
3740 (goto-char (yas/real-line-beginning))
3741 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3747 (indent-according-to-mode)
3748 (error (yas/message 3 "Warning: `yas/indent-according-to-mode' having problems running %s" indent-line-function)
3750 (mapc #'(lambda (marker)
3751 (set-marker marker (point)))
3754 (defvar yas/indent-original-column nil)
3755 (defun yas/indent (snippet)
3756 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3757 ;; Look for those $>
3759 (while (re-search-forward "$>" nil t)
3760 (delete-region (match-beginning 0) (match-end 0))
3761 (when (not (eq yas/indent-line 'auto))
3762 (yas/indent-according-to-mode snippet-markers))))
3763 ;; Now do stuff for 'fixed and 'auto
3765 (cond ((eq yas/indent-line 'fixed)
3766 (while (and (zerop (forward-line))
3767 (zerop (current-column)))
3768 (indent-to-column yas/indent-original-column)))
3769 ((eq yas/indent-line 'auto)
3770 (let ((end (set-marker (make-marker) (point-max)))
3771 (indent-first-line-p yas/also-auto-indent-first-line))
3772 (while (and (zerop (if indent-first-line-p
3775 (setq indent-first-line-p nil))
3779 (yas/indent-according-to-mode snippet-markers))))
3783 (defun yas/collect-snippet-markers (snippet)
3784 "Make a list of all the markers used by SNIPPET."
3786 (dolist (field (yas/snippet-fields snippet))
3787 (push (yas/field-start field) markers)
3788 (push (yas/field-end field) markers)
3789 (dolist (mirror (yas/field-mirrors field))
3790 (push (yas/mirror-start mirror) markers)
3791 (push (yas/mirror-end mirror) markers)))
3792 (let ((snippet-exit (yas/snippet-exit snippet)))
3793 (when (and snippet-exit
3794 (marker-buffer (yas/exit-marker snippet-exit)))
3795 (push (yas/exit-marker snippet-exit) markers)))
3798 (defun yas/real-line-beginning ()
3799 (let ((c (char-after (line-beginning-position)))
3800 (n (line-beginning-position)))
3801 (while (or (eql c ?\ )
3804 (setq c (char-after n)))
3807 (defun yas/escape-string (escaped)
3808 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3810 (defun yas/protect-escapes (&optional text escaped)
3811 "Protect all escaped characters with their numeric ASCII value.
3813 With optional string TEXT do it in string instead of buffer."
3814 (let ((changed-text text)
3815 (text-provided-p text))
3816 (mapc #'(lambda (escaped)
3818 (yas/replace-all (concat "\\" (char-to-string escaped))
3819 (yas/escape-string escaped)
3820 (when text-provided-p changed-text))))
3821 (or escaped yas/escaped-characters))
3824 (defun yas/restore-escapes (&optional text escaped)
3825 "Restore all escaped characters from their numeric ASCII value.
3827 With optional string TEXT do it in string instead of the buffer."
3828 (let ((changed-text text)
3829 (text-provided-p text))
3830 (mapc #'(lambda (escaped)
3832 (yas/replace-all (yas/escape-string escaped)
3833 (char-to-string escaped)
3834 (when text-provided-p changed-text))))
3835 (or escaped yas/escaped-characters))
3838 (defun yas/replace-backquotes ()
3839 "Replace all the \"`(lisp-expression)`\"-style expression
3840 with their evaluated value"
3841 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3842 (let ((current-string (match-string 1)) transformed)
3843 (delete-region (match-beginning 0) (match-end 0))
3844 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3845 (goto-char (match-beginning 0))
3846 (when transformed (insert transformed)))))
3848 (defun yas/scan-sexps (from count)
3850 (with-syntax-table (standard-syntax-table)
3851 (scan-sexps from count))
3855 (defun yas/make-marker (pos)
3856 "Create a marker at POS with `nil' `marker-insertion-type'"
3857 (let ((marker (set-marker (make-marker) pos)))
3858 (set-marker-insertion-type marker nil)
3861 (defun yas/field-parse-create (snippet &optional parent-field)
3862 "Parse most field expressions, except for the simple one \"$n\".
3864 The following count as a field:
3866 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3868 * \"${n: text$(expression)}, the same with a lisp expression;
3869 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3871 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3873 When multiple expressions are found, only the last one counts."
3876 (while (re-search-forward yas/field-regexp nil t)
3877 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3878 (number (and (match-string-no-properties 1)
3879 (string-to-number (match-string-no-properties 1))))
3880 (brand-new-field (and real-match-end-0
3881 ;; break if on "$(" immediately
3882 ;; after the ":", this will be
3883 ;; caught as a mirror with
3885 (not (save-match-data
3886 (eq (string-match "$[ \t\n]*("
3887 (match-string-no-properties 2)) 0)))
3888 ;; allow ${0: some exit text}
3889 ;; (not (and number (zerop number)))
3890 (yas/make-field number
3891 (yas/make-marker (match-beginning 2))
3892 (yas/make-marker (1- real-match-end-0))
3894 (when brand-new-field
3895 (goto-char real-match-end-0)
3896 (push (cons (1- real-match-end-0) real-match-end-0)
3898 (push (cons (match-beginning 0) (match-beginning 2))
3900 (push brand-new-field (yas/snippet-fields snippet))
3903 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3904 (goto-char (point-min))
3905 (yas/field-parse-create snippet brand-new-field)))))))
3906 ;; if we entered from a parent field, now search for the
3907 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3908 ;; primary field transformations
3912 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3913 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3914 ;; commit the primary field transformation if:
3916 ;; 1. we don't find it in yas/dollar-regions (a subnested
3917 ;; field) might have already caught it.
3919 ;; 2. we really make sure we have either two '$' or some
3920 ;; text and a '$' after the colon ':'. This is a FIXME: work
3921 ;; my regular expressions and end these ugly hacks.
3923 (when (and real-match-end-1
3924 (not (member (cons (match-beginning 0)
3926 yas/dollar-regions))
3928 (char-before (1- (match-beginning 1))))))
3929 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3931 (setf (yas/field-transform parent-field)
3932 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3933 (push (cons (match-beginning 0) real-match-end-1)
3934 yas/dollar-regions)))))))
3936 (defun yas/transform-mirror-parse-create (snippet)
3937 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3938 (while (re-search-forward yas/transform-mirror-regexp nil t)
3939 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3940 (number (string-to-number (match-string-no-properties 1)))
3942 (not (zerop number))
3943 (yas/snippet-find-field snippet number)))
3945 (and real-match-end-0
3947 (yas/make-mirror (yas/make-marker (match-beginning 0))
3948 (yas/make-marker (match-beginning 0))
3950 (yas/restore-escapes
3951 (buffer-substring-no-properties (match-beginning 2)
3952 (1- real-match-end-0))))))))
3953 (when brand-new-mirror
3954 (push brand-new-mirror
3955 (yas/field-mirrors field))
3956 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3957 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3959 (defun yas/simple-mirror-parse-create (snippet)
3960 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3961 (while (re-search-forward yas/simple-mirror-regexp nil t)
3962 (let ((number (string-to-number (match-string-no-properties 1))))
3963 (cond ((zerop number)
3965 (setf (yas/snippet-exit snippet)
3966 (yas/make-exit (yas/make-marker (match-end 0))))
3968 (goto-char (match-beginning 0))
3969 (when yas/wrap-around-region
3970 (cond (yas/selected-text
3971 (insert yas/selected-text))
3972 ((and (eq yas/wrap-around-region 'cua)
3975 (insert (prog1 (get-register ?0)
3976 (set-register ?0 nil))))))
3977 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3978 yas/dollar-regions)))
3980 (let ((field (yas/snippet-find-field snippet number)))
3982 (let ((brand-new-mirror (yas/make-mirror
3983 (yas/make-marker (match-beginning 0))
3984 (yas/make-marker (match-beginning 0))
3986 (push brand-new-mirror
3987 (yas/field-mirrors field))
3988 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
3989 (push (yas/make-field number
3990 (yas/make-marker (match-beginning 0))
3991 (yas/make-marker (match-beginning 0))
3993 (yas/snippet-fields snippet))))
3994 (push (cons (match-beginning 0) (match-end 0))
3995 yas/dollar-regions))))))
3997 (defun yas/delete-regions (regions)
3998 "Sort disjuct REGIONS by start point, then delete from the back."
3999 (mapc #'(lambda (reg)
4000 (delete-region (car reg) (cdr reg)))
4003 (>= (car r1) (car r2))))))
4005 (defun yas/update-mirrors (snippet)
4006 "Updates all the mirrors of SNIPPET."
4008 (let* ((fields (copy-list (yas/snippet-fields snippet)))
4009 (field (car fields)))
4011 (dolist (mirror (yas/field-mirrors field))
4012 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
4013 ;; updatte this mirror
4015 (yas/mirror-update-display mirror field)
4016 ;; for mirrors-in-fields: schedule a possible
4017 ;; parent field for reupdting later on
4019 (when mirror-parent-field
4020 (add-to-list 'fields mirror-parent-field 'append #'eq))
4021 ;; `yas/place-overlays' is needed if the active field and
4022 ;; protected overlays have been changed because of insertions
4023 ;; in `yas/mirror-update-display'
4025 (when (eq field (yas/snippet-active-field snippet))
4026 (yas/place-overlays snippet field))))
4027 (setq fields (cdr fields))
4028 (setq field (car fields))))))
4030 (defun yas/mirror-update-display (mirror field)
4031 "Update MIRROR according to FIELD (and mirror transform)."
4033 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
4034 (reflection (and (not (and mirror-parent-field
4035 (yas/field-modified-p mirror-parent-field)))
4036 (or (yas/apply-transform mirror field 'empty-on-nil)
4037 (yas/field-text-for-display field)))))
4038 (when (and reflection
4039 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
4040 (yas/mirror-end mirror)))))
4041 (goto-char (yas/mirror-start mirror))
4042 (yas/inhibit-overlay-hooks
4043 (insert reflection))
4044 (if (> (yas/mirror-end mirror) (point))
4045 (delete-region (point) (yas/mirror-end mirror))
4046 (set-marker (yas/mirror-end mirror) (point))
4047 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
4048 ;; super-special advance
4049 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
4051 (defun yas/field-update-display (field snippet)
4052 "Much like `yas/mirror-update-display', but for fields"
4053 (when (yas/field-transform field)
4054 (let ((transformed (and (not (eq (yas/field-number field) 0))
4055 (yas/apply-transform field field)))
4057 (when (and transformed
4058 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4059 (yas/field-end field)))))
4060 (setf (yas/field-modified-p field) t)
4061 (goto-char (yas/field-start field))
4062 (yas/inhibit-overlay-hooks
4063 (insert transformed)
4064 (if (> (yas/field-end field) (point))
4065 (delete-region (point) (yas/field-end field))
4066 (set-marker (yas/field-end field) (point))
4067 (yas/advance-start-maybe (yas/field-next field) (point)))
4071 ;;; Post-command hooks:
4073 (defvar yas/post-command-runonce-actions nil
4074 "List of actions to run once in `post-command-hook'.
4076 Each element of this list looks like (FN . ARGS) where FN is
4077 called with ARGS as its arguments after the currently executing
4080 After all actions have been run, this list is emptied, and after
4081 that the rest of `yas/post-command-handler' runs.")
4083 (defun yas/post-command-handler ()
4084 "Handles various yasnippet conditions after each command."
4085 (when yas/post-command-runonce-actions
4087 (mapc #'(lambda (fn-and-args)
4088 (apply (car fn-and-args)
4090 yas/post-command-runonce-actions)
4091 (error (yas/message 3 "Problem running `yas/post-command-runonce-actions'!")))
4092 (setq yas/post-command-runonce-actions nil))
4093 (cond (yas/protection-violation
4094 (goto-char yas/protection-violation)
4095 (setq yas/protection-violation nil))
4096 ((eq 'undo this-command)
4098 ;; After undo revival the correct field is sometimes not
4099 ;; restored correctly, this condition handles that
4101 (let* ((snippet (car (yas/snippets-at-point)))
4102 (target-field (and snippet
4103 (find-if-not #'(lambda (field)
4104 (yas/field-probably-deleted-p snippet field))
4106 (cons (yas/snippet-active-field snippet)
4107 (yas/snippet-fields snippet)))))))
4109 (yas/move-to-field snippet target-field))))
4110 ((not (yas/undo-in-progress))
4111 ;; When not in an undo, check if we must commit the snippet
4112 ;; (user exited it).
4113 (yas/check-commit-snippet))))
4117 (put 'yas/expand 'function-documentation
4118 '(yas/expand-from-trigger-key-doc))
4119 (defun yas/expand-from-trigger-key-doc ()
4120 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4121 (let ((fallback-description
4122 (cond ((eq yas/fallback-behavior 'call-other-command)
4123 (let* ((yas/minor-mode nil)
4124 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4126 (format " call command `%s'." (pp-to-string fallback)))
4128 ((eq yas/fallback-behavior 'return-nil)
4131 ", defer to `yas/fallback-behaviour' :-)"))))
4132 (concat "Expand a snippet before point. If no snippet
4133 expansion is possible,"
4134 fallback-description
4135 "\n\nOptional argument FIELD is for non-interactive use and is an
4136 object satisfying `yas/field-p' to restrict the expansion to.")))
4138 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4139 (defun yas/expand-from-keymap-doc ()
4140 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4141 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4142 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4143 (when (eq this-command 'describe-key)
4144 (let* ((vec (this-single-command-keys))
4145 (templates (mapcan #'(lambda (table)
4146 (yas/fetch table vec))
4147 (yas/get-snippet-tables)))
4148 (yas/direct-keymaps nil)
4149 (fallback (key-binding vec)))
4150 (concat "In this case, "
4152 (concat "these snippets are bound to this key:\n"
4153 (yas/template-pretty-list templates)
4154 "\n\nIf none of these expands, "))
4156 (format "fallback `%s' will be called." (pp-to-string fallback)))
4157 "no fallback keybinding is called."))))))
4159 (defun yas/template-pretty-list (templates)
4161 (yas/buffer-local-condition 'always))
4162 (dolist (plate templates)
4163 (setq acc (concat acc "\n*) "
4164 (propertize (concat "\\\\snippet `" (car plate) "'")
4165 'yasnippet (cdr plate)))))
4168 (define-button-type 'help-snippet-def
4169 :supertype 'help-xref
4170 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4171 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4173 (defun yas/snippet-description-finish-runonce ()
4174 "Final adjustments for the help buffer when snippets are concerned."
4175 (yas/create-snippet-xrefs)
4176 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4178 (defun yas/create-snippet-xrefs ()
4180 (goto-char (point-min))
4181 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4182 (let ((template (get-text-property (match-beginning 1)
4185 (help-xref-button 1 'help-snippet-def template)
4186 (kill-region (match-end 1) (match-end 0))
4187 (kill-region (match-beginning 0) (match-beginning 1)))))))
4189 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4190 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4192 Remaining args as in `yas/expand-snippet'."
4193 (let* ((table (gethash mode-symbol yas/tables))
4194 (yas/current-template (and table
4195 (gethash uuid (yas/table-uuidhash table)))))
4196 (when yas/current-template
4197 (yas/expand-snippet (yas/template-content yas/current-template)))))
4202 (defvar yas/verbosity 4
4203 "Log level for `yas/message' 4 means trace most anything, 0 means nothing.")
4204 (defun yas/message (level message &rest args)
4205 (when (> yas/verbosity level)
4206 (message (apply #'yas/format message args))))
4208 (defun yas/format (format-control &rest format-args)
4209 (apply #'format (concat "[yas] " format-control) format-args))
4214 ;; `locate-dominating-file'
4215 ;; `region-active-p'
4217 ;; added for compatibility in emacs < 23
4218 (unless (>= emacs-major-version 23)
4219 (unless (fboundp 'region-active-p)
4220 (defun region-active-p () (and transient-mark-mode mark-active)))
4222 (unless (fboundp 'locate-dominating-file)
4223 (defvar locate-dominating-stop-dir-regexp
4224 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4225 "Regexp of directory names which stop the search in `locate-dominating-file'.
4226 Any directory whose name matches this regexp will be treated like
4227 a kind of root directory by `locate-dominating-file' which will stop its search
4228 when it bumps into it.
4229 The default regexp prevents fruitless and time-consuming attempts to find
4230 special files in directories in which filenames are interpreted as hostnames,
4231 or mount points potentially requiring authentication as a different user.")
4233 (defun locate-dominating-file (file name)
4234 "Look up the directory hierarchy from FILE for a file named NAME.
4235 Stop at the first parent directory containing a file NAME,
4236 and return the directory. Return nil if not found."
4237 ;; We used to use the above locate-dominating-files code, but the
4238 ;; directory-files call is very costly, so we're much better off doing
4239 ;; multiple calls using the code in here.
4241 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4242 ;; `name' in /home or in /.
4243 (setq file (abbreviate-file-name file))
4246 ;; `user' is not initialized outside the loop because
4247 ;; `file' may not exist, so we may have to walk up part of the
4248 ;; hierarchy before we find the "initial UUID".
4251 (while (not (or root
4253 ;; FIXME: Disabled this heuristic because it is sometimes
4255 ;; As a heuristic, we stop looking up the hierarchy of
4256 ;; directories as soon as we find a directory belonging
4257 ;; to another user. This should save us from looking in
4258 ;; things like /net and /afs. This assumes that all the
4259 ;; files inside a project belong to the same user.
4260 ;; (let ((prev-user user))
4261 ;; (setq user (nth 2 (file-attributes file)))
4262 ;; (and prev-user (not (equal user prev-user))))
4263 (string-match locate-dominating-stop-dir-regexp file)))
4264 (setq try (file-exists-p (expand-file-name name file)))
4265 (cond (try (setq root file))
4266 ((equal file (setq prev-file file
4267 file (file-name-directory
4268 (directory-file-name file))))
4272 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4273 ;; (when it execute forward-char) and interrupt the after change
4274 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4275 ;; invoked. Here's a way to reproduce it:
4277 ;; # open a *new* Emacs.
4278 ;; # load yasnippet.
4279 ;; # open a *new* .cpp file.
4280 ;; # input "inc" and press TAB to expand the snippet.
4281 ;; # select the `#include <...>` snippet.
4282 ;; # type inside `<>`
4284 (defadvice c-neutralize-syntax-in-CPP
4285 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4286 "Adviced `c-neutralize-syntax-in-CPP' to properly
4287 handle the end-of-buffer error fired in it by calling
4288 `forward-char' at the end of buffer."
4291 (error (message (error-message-string err)))))
4293 ;; disable c-electric-* serial command in YAS fields
4294 (add-hook 'c-mode-common-hook
4296 (dolist (k '(":" ">" ";" "<" "{" "}"))
4297 (define-key (symbol-value (make-local-variable 'yas/keymap))
4298 k 'self-insert-command))))
4300 (provide 'yasnippet)
4302 ;;; yasnippet.el ends here