1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://github.com/capitaomorte/yasnippet
10 ;; Keywords: convenience, emulation
11 ;; URL: http://github.com/capitaomorte/yasnippet
12 ;; EmacsWiki: YaSnippetMode
14 ;; This file is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; This file is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
31 ;; Basic steps to setup:
33 ;; (add-to-list 'load-path
34 ;; "~/.emacs.d/plugins/yasnippet")
35 ;; (require 'yasnippet)
36 ;; (yas/global-mode 1)
39 ;; Interesting variables are:
43 ;; The directory where user-created snippets are to be
44 ;; stored. Can also be a list of directories. In that case,
45 ;; when used for bulk (re)loading of snippets (at startup or
46 ;; via `yas/reload-all'), directories appearing earlier in
47 ;; the list shadow other dir's snippets. Also, the first
48 ;; directory is taken as the default for storing the user's
51 ;; The deprecated `yas/root-directory' aliases this variable
52 ;; for backward-compatibility.
56 ;; A local variable that you can set in a hook to override
57 ;; snippet-lookup based on major mode. It is a a symbol (or
58 ;; list of symbols) that correspond to subdirectories of
59 ;; `yas/snippet-dirs' and is used for deciding which
60 ;; snippets to consider for the active buffer.
62 ;; Deprecated `yas/mode-symbol' aliases this variable for
63 ;; backward-compatibility.
65 ;; Major commands are:
69 ;; Try to expand snippets before point. In `yas/minor-mode',
70 ;; this is bound to `yas/trigger-key' which you can customize.
72 ;; M-x yas/load-directory
74 ;; Prompts you for a directory hierarchy of snippets to load.
76 ;; M-x yas/insert-snippet
78 ;; Prompts you for possible snippet expansion if that is
79 ;; possible according to buffer-local and snippet-local
80 ;; expansion conditions. With prefix argument, ignore these
83 ;; M-x yas/visit-snippet-file
85 ;; Prompts you for possible snippet expansions like
86 ;; `yas/insert-snippet', but instead of expanding it, takes
87 ;; you directly to the snippet definition's file, if it
90 ;; M-x yas/new-snippet
92 ;; Lets you create a new snippet file in the correct
93 ;; subdirectory of `yas/snippet-dirs', according to the
96 ;; M-x yas/load-snippet-buffer
98 ;; When editing a snippet, this loads the snippet. This is
99 ;; bound to "C-c C-c" while in the `snippet-mode' editing
102 ;; M-x yas/tryout-snippet
104 ;; When editing a snippet, this opens a new empty buffer,
105 ;; sets it to the appropriate major mode and inserts the
106 ;; snippet there, so you can see what it looks like. This is
107 ;; bound to "C-c C-t" while in `snippet-mode'.
109 ;; M-x yas/describe-tables
111 ;; Lists known snippets in a separate buffer. User is
112 ;; prompted as to whether only the currently active tables
113 ;; are to be displayed, or all the tables for all major
116 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
117 ;; can optionally use it the preferred "prompting method", puting in
118 ;; your .emacs file, for example:
120 ;; (require 'dropdown-list)
121 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
123 ;; yas/completing-prompt))
125 ;; Also check out the customization group
127 ;; M-x customize-group RET yasnippet RET
129 ;; If you use the customization group to set variables
130 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
131 ;; "yasnippet.el" is present in the `load-path' *before* the
132 ;; `custom-set-variables' is executed in your .emacs file.
134 ;; For more information and detailed usage, refer to the project page:
135 ;; http://github.com/capitaomorte/yasnippet
144 ;;; User customizable variables
146 (defgroup yasnippet nil
147 "Yet Another Snippet extension"
150 (defvar yas/load-file-name load-file-name
151 "Store the filename that yasnippet.el was originally loaded from.")
152 (defcustom yas/snippet-dirs (remove nil
153 (list "~/.emacs.d/snippets"
154 (when yas/load-file-name
155 (concat (file-name-directory yas/load-file-name) "snippets"))))
156 "Directory or list of snippet dirs for each major mode.
158 The directory where user-created snippets are to be stored. Can
159 also be a list of directories. In that case, when used for
160 bulk (re)loading of snippets (at startup or via
161 `yas/reload-all'), directories appearing earlier in the list
162 shadow other dir's snippets. Also, the first directory is taken
163 as the default for storing the user's new snippets."
164 :type '(choice (string :tag "Single directory (string)")
165 (repeat :args (string) :tag "List of directories (strings)"))
168 :set #'(lambda (symbol new)
169 (let ((old (and (boundp symbol)
170 (symbol-value symbol))))
171 (set-default symbol new)
172 (unless (or (not (fboundp 'yas/reload-all))
175 (defun yas/snippet-dirs ()
176 "Returns `yas/snippet-dirs' (which see) as a list."
177 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
178 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
180 (defcustom yas/prompt-functions '(yas/x-prompt
182 yas/completing-prompt
185 "Functions to prompt for keys, templates, etc interactively.
187 These functions are called with the following arguments:
189 - PROMPT: A string to prompt the user
191 - CHOICES: a list of strings or objects.
193 - optional DISPLAY-FN : A function that, when applied to each of
194 the objects in CHOICES will return a string.
196 The return value of any function you put here should be one of
197 the objects in CHOICES, properly formatted with DISPLAY-FN (if
200 - To signal that your particular style of prompting is
201 unavailable at the moment, you can also have the function return
204 - To signal that the user quit the prompting process, you can
207 (signal 'quit \"user quit!\")."
208 :type '(repeat function)
211 (defcustom yas/indent-line 'auto
212 "Controls indenting applied to a recent snippet expansion.
214 The following values are possible:
216 - `fixed' Indent the snippet to the current column;
218 - `auto' Indent each line of the snippet with `indent-according-to-mode'
220 Every other value means don't apply any snippet-side indendation
221 after expansion (the manual per-line \"$>\" indentation still
223 :type '(choice (const :tag "Nothing" nothing)
224 (const :tag "Fixed" fixed)
225 (const :tag "Auto" auto))
228 (defcustom yas/also-auto-indent-first-line nil
229 "Non-nil means also auto indent first line according to mode.
231 Naturally this is only valid when `yas/indent-line' is `auto'"
235 (defcustom yas/snippet-revival t
236 "Non-nil means re-activate snippet fields after undo/redo."
240 (defcustom yas/trigger-key "TAB"
241 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
243 Value is a string that is converted to the internal Emacs key
244 representation using `read-kbd-macro'."
247 :set #'(lambda (symbol key)
248 (let ((old (and (boundp symbol)
249 (symbol-value symbol))))
250 (set-default symbol key)
251 ;; On very first loading of this defcustom,
252 ;; `yas/trigger-key' is *not* loaded.
253 (if (fboundp 'yas/trigger-key-reload)
254 (yas/trigger-key-reload old)))))
256 (defcustom yas/next-field-key '("TAB" "<tab>")
257 "The key to navigate to next field when a snippet is active.
259 Value is a string that is converted to the internal Emacs key
260 representation using `read-kbd-macro'.
262 Can also be a list of strings."
263 :type '(choice (string :tag "String")
264 (repeat :args (string) :tag "List of strings"))
266 :set #'(lambda (symbol val)
267 (set-default symbol val)
268 (if (fboundp 'yas/init-yas-in-snippet-keymap)
269 (yas/init-yas-in-snippet-keymap))))
272 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
273 "The key to navigate to previous field when a snippet is active.
275 Value is a string that is converted to the internal Emacs key
276 representation using `read-kbd-macro'.
278 Can also be a list of strings."
279 :type '(choice (string :tag "String")
280 (repeat :args (string) :tag "List of strings"))
282 :set #'(lambda (symbol val)
283 (set-default symbol val)
284 (if (fboundp 'yas/init-yas-in-snippet-keymap)
285 (yas/init-yas-in-snippet-keymap))))
287 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
288 "The key to clear the currently active field.
290 Value is a string that is converted to the internal Emacs key
291 representation using `read-kbd-macro'.
293 Can also be a list of strings."
294 :type '(choice (string :tag "String")
295 (repeat :args (string) :tag "List of strings"))
297 :set #'(lambda (symbol val)
298 (set-default symbol val)
299 (if (fboundp 'yas/init-yas-in-snippet-keymap)
300 (yas/init-yas-in-snippet-keymap))))
302 (defcustom yas/triggers-in-field nil
303 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
305 Otherwise, `yas/next-field-key' just tries to move on to the next
310 (defcustom yas/fallback-behavior 'call-other-command
311 "How to act when `yas/trigger-key' does *not* expand a snippet.
313 - `call-other-command' means try to temporarily disable YASnippet
314 and call the next command bound to `yas/trigger-key'.
316 - nil or the symbol `return-nil' mean do nothing. (and
317 `yas/expand-returns' nil)
319 - A lisp form (apply COMMAND . ARGS) means interactively call
320 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
321 with ARGS as arguments."
322 :type '(choice (const :tag "Call previous command" call-other-command)
323 (const :tag "Do nothing" return-nil))
326 (defcustom yas/choose-keys-first nil
327 "If non-nil, prompt for snippet key first, then for template.
329 Otherwise prompts for all possible snippet names.
331 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
335 (defcustom yas/choose-tables-first nil
336 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
338 Otherwise, user chooses between the merging together of all
341 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
345 (defcustom yas/use-menu 'abbreviate
346 "Display a YASnippet menu in the menu bar.
348 When non-nil, submenus for each snippet table will be listed
349 under the menu \"Yasnippet\".
351 - If set to `real-modes' only submenus whose name more or less
352 corresponds to a major mode are listed.
354 - If set to `abbreviate', only the current major-mode
355 menu and the modes set in `yas/extra-modes' are listed.
357 Any other non-nil value, every submenu is listed."
358 :type '(choice (const :tag "Full" t)
359 (const :tag "Real modes only" real-modes)
360 (const :tag "Abbreviate" abbreviate))
363 (defcustom yas/trigger-symbol " =>"
364 "The text that will be used in menu to represent the trigger."
368 (defcustom yas/wrap-around-region nil
369 "If non-nil, snippet expansion wraps around selected region.
371 The wrapping occurs just before the snippet's exit marker. This
372 can be overriden on a per-snippet basis."
376 (defcustom yas/good-grace t
377 "If non-nil, don't raise errors in inline elisp evaluation.
379 An error string \"[yas] error\" is returned instead."
383 (defcustom yas/visit-from-menu nil
384 "If non-nil visit snippets's files from menu, instead of expanding them.
386 This cafn only work when snippets are loaded from files."
390 (defcustom yas/expand-only-for-last-commands nil
391 "List of `last-command' values to restrict tab-triggering to, or nil.
393 Leave this set at nil (the default) to be able to trigger an
394 expansion simply by placing the cursor after a valid tab trigger,
395 using whichever commands.
397 Optionallly, set this to something like '(self-insert-command) if
398 you to wish restrict expansion to only happen when the last
399 letter of the snippet tab trigger was typed immediately before
400 the trigger key itself."
401 :type '(repeat function)
404 ;; Only two faces, and one of them shouldn't even be used...
406 (defface yas/field-highlight-face
407 '((t (:inherit 'region)))
408 "The face used to highlight the currently active field of a snippet"
411 (defface yas/field-debug-face
413 "The face used for debugging some overlays normally hidden"
417 ;;; User can also customize the next defvars
418 (defun yas/define-some-keys (keys keymap definition)
419 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
420 (let ((keys (or (and (listp keys) keys)
423 (define-key keymap (read-kbd-macro key) definition))))
426 (let ((map (make-sparse-keymap)))
427 (mapc #'(lambda (binding)
428 (yas/define-some-keys (car binding) map (cdr binding)))
429 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
430 (,yas/prev-field-key . yas/prev-field)
431 ("C-g" . yas/abort-snippet)
432 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
434 "The keymap active while a snippet expansion is in progress.")
436 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
437 "List of character syntaxes used to find a trigger key before point.
438 The list is tried in the order while scanning characters
439 backwards from point. For example, if the list is '(\"w\" \"w_\")
440 first look for trigger keys which are composed exclusively of
441 \"word\"-syntax characters, and then, if that fails, look for
442 keys which are either of \"word\" or \"symbol\"
443 syntax. Triggering after
447 will, according to the \"w\" element first try \"bar\". If that
448 isn't a trigger key, \"foo-bar\" is tried, respecting a second
451 (defvar yas/after-exit-snippet-hook
453 "Hooks to run after a snippet exited.
455 The hooks will be run in an environment where some variables bound to
458 `yas/snippet-beg' : The beginning of the region of the snippet.
460 `yas/snippet-end' : Similar to beg.
462 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
464 (defvar yas/before-expand-snippet-hook
466 "Hooks to run just before expanding a snippet.")
468 (defvar yas/buffer-local-condition
469 '(if (and (or (fourth (syntax-ppss))
470 (fifth (syntax-ppss)))
471 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
472 '(require-snippet-condition . force-in-comment)
474 "Snippet expanding condition.
476 This variable is a lisp form which is evaluated everytime a
477 snippet expansion is attemped:
479 * If it evaluates to nil, no snippets can be expanded.
481 * If it evaluates to the a cons (require-snippet-condition
484 * Snippets bearing no \"# condition:\" directive are not
487 * Snippets bearing conditions that evaluate to nil (or
488 produce an error) won't be onsidered.
490 * If the snippet has a condition that evaluates to non-nil
493 * If REQUIREMENT is t, the snippet is considered
495 * If REQUIREMENT is `eq' RESULT, the snippet is
498 * Otherwise, the snippet is not considered.
500 * If it evaluates to the symbol 'always, all snippets are
501 considered for expansion, regardless of any conditions.
503 * If it evaluates to t or some other non-nil value
505 * Snippet bearing no conditions, or conditions that
506 evaluate to non-nil, are considered for expansion.
508 * Otherwise, the snippet is not considered.
510 Here's an example preventing snippets from being expanded from
511 inside comments, in `python-mode' only, with the exception of
512 snippets returning the symbol 'force-in-comment in their
515 (add-hook 'python-mode-hook
517 (setq yas/buffer-local-condition
518 '(if (python-in-string/comment)
519 '(require-snippet-condition . force-in-comment)
522 The default value is similar, it filters out potential snippet
523 expansions inside comments and string literals, unless the
524 snippet itself contains a condition that returns the symbol
525 `force-in-comment'.")
528 ;;; Internal variables
530 (defvar yas/version "0.7.0")
532 (defvar yas/menu-table (make-hash-table)
533 "A hash table of MAJOR-MODE symbols to menu keymaps.")
535 (defvar yas/known-modes
536 '(ruby-mode rst-mode markdown-mode)
537 "A list of mode which is well known but not part of emacs.")
539 (defvar yas/escaped-characters
540 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
541 "List of characters which *might* need to be escaped.")
543 (defconst yas/field-regexp
544 "${\\([0-9]+:\\)?\\([^}]*\\)}"
545 "A regexp to *almost* recognize a field.")
547 (defconst yas/multi-dollar-lisp-expression-regexp
548 "$+[ \t\n]*\\(([^)]*)\\)"
549 "A regexp to *almost* recognize a \"$(...)\" expression.")
551 (defconst yas/backquote-lisp-expression-regexp
553 "A regexp to recognize a \"`lisp-expression`\" expression." )
555 (defconst yas/transform-mirror-regexp
556 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
557 "A regexp to *almost* recognize a mirror with a transform.")
559 (defconst yas/simple-mirror-regexp
561 "A regexp to recognize a simple mirror.")
563 (defvar yas/snippet-id-seed 0
564 "Contains the next id for a snippet.")
566 (defun yas/snippet-next-id ()
567 (let ((id yas/snippet-id-seed))
568 (incf yas/snippet-id-seed)
574 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
575 (defvar last-buffer-undo-list nil)
577 (defvar yas/minor-mode-menu nil
578 "Holds the YASnippet menu")
580 (defun yas/init-minor-keymap ()
581 (let ((map (make-sparse-keymap)))
582 (easy-menu-define yas/minor-mode-menu
584 "Menu used when YAS/minor-mode is active."
587 ["Expand trigger" yas/expand
588 :help "Possibly expand tab trigger before point"]
589 ["Insert at point..." yas/insert-snippet
590 :help "Prompt for an expandable snippet and expand it at point"]
591 ["New snippet..." yas/new-snippet
592 :help "Create a new snippet in an appropriate directory"]
593 ["Visit snippet file..." yas/visit-snippet-file
594 :help "Prompt for an expandable snippet and find its file"]
596 ("Snippet menu behaviour"
597 ["Visit snippets" (setq yas/visit-from-menu t)
598 :help "Visit snippets from the menu"
599 :active t :style radio :selected yas/visit-from-menu]
600 ["Expand snippets" (setq yas/visit-from-menu nil)
601 :help "Expand snippets from the menu"
602 :active t :style radio :selected (not yas/visit-from-menu)]
604 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
605 :help "Show snippet submenus for modes that appear to be real major modes"
606 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
607 ["Show all modes" (setq yas/use-menu 't)
608 :help "Show one snippet submenu for each loaded table"
609 :active t :style radio :selected (eq yas/use-menu 't)]
610 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
611 :help "Show only snippet submenus for the current active modes"
612 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
614 ["Auto" (setq yas/indent-line 'auto)
615 :help "Indent each line of the snippet with `indent-according-to-mode'"
616 :active t :style radio :selected (eq yas/indent-line 'auto)]
617 ["Fixed" (setq yas/indent-line 'fixed)
618 :help "Indent the snippet to the current column"
619 :active t :style radio :selected (eq yas/indent-line 'fixed)]
620 ["None" (setq yas/indent-line 'none)
621 :help "Don't apply any particular snippet indentation after expansion"
622 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
624 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
625 (not yas/also-auto-indent-first-line))
626 :help "When auto-indenting also, auto indent the first line menu"
627 :active (eq yas/indent-line 'auto)
628 :style toggle :selected yas/also-auto-indent-first-line]
631 ["System X-widget" (setq yas/prompt-functions
633 (remove 'yas/x-prompt
634 yas/prompt-functions)))
635 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
636 :active t :style radio :selected (eq (car yas/prompt-functions)
638 ["Dropdown-list" (setq yas/prompt-functions
639 (cons 'yas/dropdown-prompt
640 (remove 'yas/dropdown-prompt
641 yas/prompt-functions)))
642 :help "Use a special dropdown list"
643 :active t :style radio :selected (eq (car yas/prompt-functions)
644 'yas/dropdown-prompt)]
645 ["Ido" (setq yas/prompt-functions
646 (cons 'yas/ido-prompt
647 (remove 'yas/ido-prompt
648 yas/prompt-functions)))
649 :help "Use an ido-style minibuffer prompt"
650 :active t :style radio :selected (eq (car yas/prompt-functions)
652 ["Completing read" (setq yas/prompt-functions
653 (cons 'yas/completing-prompt
654 (remove 'yas/completing-prompt-prompt
655 yas/prompt-functions)))
656 :help "Use a normal minibuffer prompt"
657 :active t :style radio :selected (eq (car yas/prompt-functions)
658 'yas/completing-prompt-prompt)]
661 ["Wrap region in exit marker"
662 (setq yas/wrap-around-region
663 (not yas/wrap-around-region))
664 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
665 :style toggle :selected yas/wrap-around-region]
666 ["Allow stacked expansions "
667 (setq yas/triggers-in-field
668 (not yas/triggers-in-field))
669 :help "If non-nil allow snippets to be triggered inside other snippet fields"
670 :style toggle :selected yas/triggers-in-field]
671 ["Revive snippets on undo "
672 (setq yas/snippet-revival
673 (not yas/snippet-revival))
674 :help "If non-nil allow snippets to become active again after undo"
675 :style toggle :selected yas/snippet-revival]
678 (not yas/good-grace))
679 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
680 :style toggle :selected yas/good-grace]
683 ["Load snippets..." yas/load-directory
684 :help "Load snippets from a specific directory"]
685 ["Reload everything" yas/reload-all
686 :help "Cleanup stuff, reload snippets, rebuild menus"]
688 :help "Display some information about YASsnippet"]))
689 ;; Now for the stuff that has direct keybindings
691 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
692 (define-key map "\C-c&\C-n" 'yas/new-snippet)
693 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
696 (defvar yas/minor-mode-map (yas/init-minor-keymap)
697 "The keymap used when `yas/minor-mode' is active.")
699 (defun yas/trigger-key-reload (&optional unbind-key)
700 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
702 With optional UNBIND-KEY, try to unbind that key from
703 `yas/minor-mode-map'."
704 (when (and unbind-key
706 (not (string= unbind-key "")))
707 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
708 (when (and yas/trigger-key
709 (stringp yas/trigger-key)
710 (not (string= yas/trigger-key "")))
711 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
713 (defvar yas/tables (make-hash-table)
714 "A hash table of mode symbols to `yas/table' objects.")
716 (defvar yas/parents (make-hash-table)
717 "A hash table of mode symbols do lists of direct parent mode symbols.
719 This list is populated when reading the \".yas-parents\" files
720 found when traversing snippet directories with
721 `yas/load-directory'.
723 There might be additionalal parenting information stored in the
724 `derived-mode-parent' property of some mode symbols, but that is
727 (defvar yas/direct-keymaps (list)
728 "Keymap alist supporting direct snippet keybindings.
730 This variable is is placed in `emulation-mode-map-alists'.
732 Its elements looks like (TABLE-NAME . KEYMAP). They're
733 instantiated on `yas/reload-all' but KEYMAP is added to only when
734 loading snippets. `yas//direct-TABLE-NAME' is then a variable set
735 buffer-locally when entering `yas/minor-mode'. KEYMAP binds all
736 defined direct keybindings to the command
737 `yas/expand-from-keymap' which then which snippet to expand.")
739 (defun yas/direct-keymaps-reload ()
740 "Force reload the direct keybinding for active snippet tables."
742 (setq yas/direct-keymaps nil)
743 (maphash #'(lambda (name table)
744 (push (cons (intern (format "yas//direct-%s" name))
745 (yas/table-direct-keymap table))
749 (defun yas/modes-to-activate ()
750 "Compute list of mode symbols that are active for `yas/expand'
752 (let ((modes-to-activate (list major-mode))
754 (while (setq mode (get mode 'derived-mode-parent))
755 (push mode modes-to-activate))
756 (dolist (mode (yas/extra-modes))
757 (push mode modes-to-activate))
759 (append modes-to-activate
760 (mapcan #'(lambda (mode)
761 (yas/all-parents mode))
762 modes-to-activate)))))
764 (defvar yas/minor-mode-hook nil
765 "Hook run when yas/minor-mode is turned on")
768 (define-minor-mode yas/minor-mode
769 "Toggle YASnippet mode.
771 When YASnippet mode is enabled, the `yas/trigger-key' key expands
772 snippets of code depending on the mode.
774 With no argument, this command toggles the mode.
775 positive prefix argument turns on the mode.
776 Negative prefix argument turns off the mode.
778 You can customize the key through `yas/trigger-key'.
781 \\{yas/minor-mode-map}"
783 ;; The indicator for the mode line.
786 (cond (yas/minor-mode
787 ;; Reload the trigger key
789 (yas/trigger-key-reload)
790 ;; Install the direct keymaps in `emulation-mode-map-alists'
791 ;; (we use `add-hook' even though it's not technically a hook,
792 ;; but it works). Then define variables named after modes to
793 ;; index `yas/direct-keymaps'.
795 ;; Also install the post-command-hook.
797 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
798 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
799 ;; Set the `yas//direct-%s' vars for direct keymap expansion
801 (dolist (mode (yas/modes-to-activate))
802 (let ((name (intern (format "yas//direct-%s" mode))))
803 (set-default name nil)
804 (set (make-local-variable name) t)))
807 (yas/load-pending-jits))
809 ;; Uninstall the direct keymaps and the post-command hook
811 (remove-hook 'post-command-hook 'yas/post-command-handler t)
812 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
815 (defvar yas/dont-activate nil
816 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
818 `yas/minor-mode-on' is usually called by `yas/global-mode' so
819 this effectively lets you define exceptions to the \"global\"
820 behaviour. Can also be a function of zero arguments.")
821 (make-variable-buffer-local 'yas/dont-activate)
823 (defun yas/minor-mode-on ()
824 "Turn on YASnippet minor mode.
826 Do this unless `yas/dont-activate' is truish "
828 (unless (or (minibufferp)
829 (if (functionp yas/dont-activate)
830 (funcall yas/dont-activate)
832 ;; Load all snippets definitions unless we still don't have a
833 ;; root-directory or some snippets have already been loaded.
838 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
842 (defadvice yas/global-mode (before yas/reload-with-jit (arg) activate)
846 ;; explicitly enabling
848 ((not yas/global-mode)
852 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
855 (defvar yas/font-lock-keywords
856 (append '(("^#.*$" . font-lock-comment-face))
857 lisp-font-lock-keywords
858 lisp-font-lock-keywords-1
859 lisp-font-lock-keywords-2
861 (0 font-lock-keyword-face)
862 (1 font-lock-string-face t))
864 (0 font-lock-keyword-face)
865 (1 font-lock-warning-face t))
866 ("${" font-lock-keyword-face)
867 ("$[0-9]+?" font-lock-preprocessor-face)
868 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
870 (0 font-lock-keyword-face)))))
872 (defun yas/init-major-keymap ()
873 (let ((map (make-sparse-keymap)))
874 (easy-menu-define nil
876 "Menu used when snippet-mode is active."
878 (mapcar #'(lambda (ent)
880 (define-key map (third ent) (second ent)))
881 (vector (first ent) (second ent) t))
883 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
884 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
887 (defvar snippet-mode-map
888 (yas/init-major-keymap)
889 "The keymap used when `snippet-mode' is active")
892 (define-derived-mode snippet-mode text-mode "Snippet"
893 "A mode for editing yasnippets"
894 (setq font-lock-defaults '(yas/font-lock-keywords))
895 (set (make-local-variable 'require-final-newline) nil)
896 (set (make-local-variable 'comment-start) "#")
897 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
901 ;;; Internal structs for template management
903 (defstruct (yas/template (:constructor yas/make-blank-template))
904 "A template for a snippet."
914 group ;; as dictated by the #group: directive or .yas-make-groups
915 perm-group ;; as dictated by `yas/define-menu'
919 (defun yas/populate-template (template &rest args)
920 "Helper function to populate a template with properties"
924 (position (intern (substring (symbol-name (car args)) 1))
925 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
927 (setq args (cddr args)))
930 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
931 "A table to store snippets for a particular mode.
933 Has the following fields:
937 A symbol name normally corresponding to a major mode, but can
938 also be a pseudo major-mode to be referenced in
939 `yas/extra-modes', for example.
943 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
944 a string or a vector, where the former is the snippet's trigger
945 and the latter means it's a direct keybinding. NAMEHASH is yet
946 another hash of (NAME . TEMPLATE) where NAME is the snippet's
947 name and TEMPLATE is a `yas/template' object.
949 `yas/table-direct-keymap'
951 A keymap for the snippets in this table that have direct
952 keybindings. This is kept in sync with the keyhash, i.e., all
953 the elements of the keyhash that are vectors appear here as
954 bindings to `yas/expand-from-keymap'.
958 A hash table mapping snippets uuid's to the same `yas/template'
959 objects. A snippet uuid defaults to the snippet's name.
962 (hash (make-hash-table :test 'equal))
963 (uuidhash (make-hash-table :test 'equal))
965 (direct-keymap (make-sparse-keymap)))
967 (defun yas/get-template-by-uuid (mode uuid)
968 "Find the snippet template in MODE by its UUID."
969 (let* ((table (gethash mode yas/tables mode)))
971 (gethash uuid (yas/table-uuidhash table)))))
973 ;; Apropos storing/updating, this works with two steps:
975 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
978 ;; 2. `yas/add-template' to add the mappings again:
980 ;; Create or index the entry in TABLES's `yas/table-hash'
981 ;; linking KEY to a namehash. That namehash links NAME to
982 ;; TEMPLATE, and is also created a new namehash inside that
985 (defun yas/remove-template-by-uuid (table uuid)
986 "Remove from TABLE a template identified by UUID."
987 (let ((template (gethash uuid (yas/table-uuidhash table))))
989 (let* ((name (yas/template-name template))
991 ;; Remove the name from each of the targeted namehashes
993 (maphash #'(lambda (k v)
994 (let ((template (gethash name v)))
996 (eq uuid (yas/template-uuid template)))
998 (when (zerop (hash-table-count v))
999 (push k empty-keys)))))
1000 (yas/table-hash table))
1001 ;; Remove the namehashed themselves if they've become empty
1003 (dolist (key empty-keys)
1004 (remhash key (yas/table-hash table)))
1006 ;; Finally, remove the uuid from the uuidhash
1008 (remhash uuid (yas/table-uuidhash table))))))
1010 (defun yas/add-template (table template)
1011 "Store in TABLE the snippet template TEMPLATE.
1013 KEY can be a string (trigger key) of a vector (direct
1015 (let ((name (yas/template-name template))
1016 (key (yas/template-key template))
1017 (keybinding (yas/template-keybinding template))
1018 (menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1019 (dolist (k (remove nil (list key keybinding)))
1023 (yas/table-hash table))
1025 (make-hash-table :test 'equal)
1026 (yas/table-hash table))))
1028 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1030 ;; Update trigger & keybinding in the menu-binding pair
1032 (setf (getf (cdr (car menu-binding-pair)) :keys)
1033 (or (and keybinding (key-description keybinding))
1034 (and key (concat key yas/trigger-symbol))))
1036 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1038 (defun yas/update-template (table template)
1039 "Add or update TEMPLATE in TABLE.
1041 Also takes care of adding and updating to the associated menu."
1042 ;; Remove from table by uuid
1044 (yas/remove-template-by-uuid table (yas/template-uuid template))
1045 ;; Add to table again
1047 (yas/add-template table template)
1048 ;; Take care of the menu
1050 (let ((keymap (yas/menu-keymap-get-create table))
1051 (group (yas/template-group template)))
1052 (when (and yas/use-menu
1054 (not (cdr (yas/template-menu-binding-pair template))))
1055 ;; Remove from menu keymap
1057 (yas/delete-from-keymap keymap (yas/template-uuid template))
1059 ;; Add necessary subgroups as necessary.
1061 (dolist (subgroup group)
1062 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1063 (unless (and subgroup-keymap
1064 (keymapp subgroup-keymap))
1065 (setq subgroup-keymap (make-sparse-keymap))
1066 (define-key keymap (vector (make-symbol subgroup))
1067 `(menu-item ,subgroup ,subgroup-keymap)))
1068 (setq keymap subgroup-keymap)))
1070 ;; Add this entry to the keymap
1072 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1073 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1075 (defun yas/namehash-templates-alist (namehash)
1077 (maphash #'(lambda (k v)
1078 (push (cons k v) alist))
1082 (defun yas/fetch (table key)
1083 "Fetch templates in TABLE by KEY.
1085 Return a list of cons (NAME . TEMPLATE) where NAME is a
1086 string and TEMPLATE is a `yas/template' structure."
1087 (let* ((keyhash (yas/table-hash table))
1088 (namehash (and keyhash (gethash key keyhash))))
1090 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1093 ;;; Filtering/condition logic
1095 (defun yas/eval-condition (condition)
1102 (yas/message 1 "Error in condition evaluation: %s" (error-message-string err))
1106 (defun yas/filter-templates-by-condition (templates)
1107 "Filter the templates using the applicable condition.
1109 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1110 string and TEMPLATE is a `yas/template' structure.
1112 This function implements the rules described in
1113 `yas/buffer-local-condition'. See that variables documentation."
1114 (let ((requirement (yas/require-template-specific-condition-p)))
1115 (if (eq requirement 'always)
1117 (remove-if-not #'(lambda (pair)
1118 (yas/template-can-expand-p
1119 (yas/template-condition (cdr pair)) requirement))
1122 (defun yas/require-template-specific-condition-p ()
1123 "Decides if this buffer requests/requires snippet-specific
1124 conditions to filter out potential expansions."
1125 (if (eq 'always yas/buffer-local-condition)
1127 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1128 (yas/eval-condition yas/buffer-local-condition))
1129 yas/buffer-local-condition)))
1130 (when local-condition
1131 (if (eq local-condition t)
1133 (and (consp local-condition)
1134 (eq 'require-snippet-condition (car local-condition))
1135 (symbolp (cdr local-condition))
1136 (cdr local-condition)))))))
1138 (defun yas/template-can-expand-p (condition requirement)
1139 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1140 (let* ((result (or (null condition)
1141 (yas/eval-condition condition))))
1142 (cond ((eq requirement t)
1145 (eq requirement result)))))
1147 (defun yas/all-parents (mode)
1148 "Returns a list of all parent modes of MODE"
1149 (let ((parents (gethash mode yas/parents)))
1151 (mapcan #'yas/all-parents parents))))
1153 (defun yas/table-templates (table)
1156 (maphash #'(lambda (key namehash)
1157 (maphash #'(lambda (name template)
1158 (push (cons name template) acc))
1160 (yas/table-hash table))
1161 (yas/filter-templates-by-condition acc))))
1163 (defun yas/current-key ()
1164 "Get the key under current position. A key is used to find
1165 the template of a snippet in the current snippet-table."
1166 (let ((start (point))
1168 (syntaxes yas/key-syntaxes)
1172 (while (and (not done) syntaxes)
1173 (setq syntax (car syntaxes))
1174 (setq syntaxes (cdr syntaxes))
1176 (skip-syntax-backward syntax)
1177 (setq start (point)))
1179 (mapcan #'(lambda (table)
1180 (yas/fetch table (buffer-substring-no-properties start end)))
1181 (yas/get-snippet-tables)))
1190 (defun yas/table-all-keys (table)
1193 (maphash #'(lambda (key namehash)
1194 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1196 (yas/table-hash table))
1200 ;;; Internal functions
1202 (defun yas/real-mode? (mode)
1203 "Try to find out if MODE is a real mode. The MODE bound to
1204 a function (like `c-mode') is considered real mode. Other well
1205 known mode like `ruby-mode' which is not part of Emacs might
1206 not bound to a function until it is loaded. So yasnippet keeps
1207 a list of modes like this to help the judgement."
1209 (find mode yas/known-modes)))
1211 (defun yas/eval-lisp (form)
1212 "Evaluate FORM and convert the result to string."
1213 (let ((retval (catch 'yas/exception
1219 (let ((result (eval form)))
1221 (format "%s" result))))))
1222 (error (if yas/good-grace
1223 (yas/format "elisp error! %s" (error-message-string err))
1224 (error (yas/format "elisp error: %s"
1225 (error-message-string err)))))))))
1226 (when (and (consp retval)
1227 (eq 'yas/exception (car retval)))
1228 (error (cdr retval)))
1231 (defun yas/eval-lisp-no-saves (form)
1234 (error (if yas/good-grace
1235 (yas/format "elisp error! %s" (error-message-string err))
1236 (error (yas/format "elisp error: %s"
1237 (error-message-string err)))))))
1239 (defun yas/read-lisp (string &optional nil-on-error)
1240 "Read STRING as a elisp expression and return it.
1242 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1243 return an expression that when evaluated will issue an error."
1246 (error (and (not nil-on-error)
1247 `(error (error-message-string ,err))))))
1249 (defun yas/read-keybinding (keybinding)
1250 "Read KEYBINDING as a snippet keybinding, return a vector."
1251 (when (and keybinding
1252 (not (string-match "keybinding" keybinding)))
1254 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1256 (read-kbd-macro keybinding 'need-vector))))
1259 (yas/message 3 "warning: keybinding \"%s\" invalid since %s."
1260 keybinding (error-message-string err))
1263 (defvar yas/extra-modes nil
1264 "If non-nil, also lookup snippets for this/these modes.
1266 Can be a symbol or a list of symbols.
1268 This variable probably makes more sense as buffer-local, so
1269 ensure your use `make-local-variable' when you set it.")
1270 (defun yas/extra-modes ()
1271 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1272 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1274 (defun yas/table-get-create (mode)
1275 "Get or create the snippet table corresponding to MODE."
1276 (let ((table (gethash mode
1279 (setq table (yas/make-snippet-table (symbol-name mode)))
1280 (puthash mode table yas/tables)
1281 (push (cons (intern (format "yas//direct-%s" mode))
1282 (yas/table-direct-keymap table))
1283 yas/direct-keymaps))
1286 (defun yas/get-snippet-tables ()
1287 "Get snippet tables for current buffer.
1289 Return a list of `yas/table' objects. The list of modes to
1290 consider is returned by `yas/modes-to-activate'"
1292 (mapcar #'(lambda (mode-name)
1293 (gethash mode-name yas/tables))
1294 (yas/modes-to-activate))))
1296 (defun yas/menu-keymap-get-create (table)
1297 "Get or create the main menu keymap correspondong to MODE.
1299 This may very well create a plethora of menu keymaps and arrange
1300 them in all `yas/menu-table'"
1301 (let* ((mode (intern (yas/table-name table)))
1302 (menu-keymap (or (gethash mode yas/menu-table)
1303 (puthash mode (make-sparse-keymap) yas/menu-table)))
1304 (parents (yas/table-parents table)))
1305 (mapc #'yas/menu-keymap-get-create parents)
1306 (define-key yas/minor-mode-menu (vector mode)
1307 `(menu-item ,(symbol-name mode) ,menu-keymap
1308 :visible (yas/show-menu-p ',mode)))
1311 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1312 ;;; Template-related and snippet loading functions
1314 (defun yas/parse-template (&optional file)
1315 "Parse the template in the current buffer.
1317 Optional FILE is the absolute file name of the file being
1320 Optional GROUP is the group where the template is to go,
1321 otherwise we attempt to calculate it from FILE.
1323 Return a snippet-definition, i.e. a list
1325 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1327 If the buffer contains a line of \"# --\" then the contents above
1328 this line are ignored. Directives can set most of these with the syntax:
1330 # directive-name : directive-value
1332 Here's a list of currently recognized directives:
1343 (goto-char (point-min))
1344 (let* ((type 'snippet)
1346 (file-name-nondirectory file)))
1352 (yas/calculate-group file)))
1356 (if (re-search-forward "^# --\n" nil t)
1357 (progn (setq template
1358 (buffer-substring-no-properties (point)
1360 (setq bound (point))
1361 (goto-char (point-min))
1362 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1363 (when (string= "uuid" (match-string-no-properties 1))
1364 (setq uuid (match-string-no-properties 2)))
1365 (when (string= "type" (match-string-no-properties 1))
1366 (setq type (if (string= "command" (match-string-no-properties 2))
1369 (when (string= "key" (match-string-no-properties 1))
1370 (setq key (match-string-no-properties 2)))
1371 (when (string= "name" (match-string-no-properties 1))
1372 (setq name (match-string-no-properties 2)))
1373 (when (string= "condition" (match-string-no-properties 1))
1374 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1375 (when (string= "group" (match-string-no-properties 1))
1376 (setq group (match-string-no-properties 2)))
1377 (when (string= "expand-env" (match-string-no-properties 1))
1378 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1380 (when (string= "binding" (match-string-no-properties 1))
1381 (setq binding (match-string-no-properties 2)))))
1383 (buffer-substring-no-properties (point-min) (point-max))))
1384 (unless (or key binding)
1385 (setq key (and file (file-name-nondirectory file))))
1386 (when (eq type 'command)
1387 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1389 (setq group (split-string group "\\.")))
1390 (list key template name condition group expand-env file binding uuid)))
1392 (defun yas/calculate-group (file)
1393 "Calculate the group for snippet file path FILE."
1394 (let* ((dominating-dir (locate-dominating-file file
1395 ".yas-make-groups"))
1396 (extra-path (and dominating-dir
1397 (replace-regexp-in-string (concat "^"
1398 (expand-file-name dominating-dir))
1400 (expand-file-name file))))
1401 (extra-dir (and extra-path
1402 (file-name-directory extra-path)))
1403 (group (and extra-dir
1404 (replace-regexp-in-string "/"
1406 (directory-file-name extra-dir)))))
1409 (defun yas/subdirs (directory &optional filep)
1410 "Return subdirs or files of DIRECTORY according to FILEP."
1411 (remove-if (lambda (file)
1412 (or (string-match "^\\."
1413 (file-name-nondirectory file))
1414 (string-match "^#.*#$"
1415 (file-name-nondirectory file))
1417 (file-name-nondirectory file))
1419 (file-directory-p file)
1420 (not (file-directory-p file)))))
1421 (directory-files directory t)))
1423 (defun yas/make-menu-binding (template)
1424 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1425 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1427 (defun yas/expand-or-visit-from-menu (mode uuid)
1428 (let* ((table (yas/table-get-create mode))
1429 (yas/current-template (and table
1430 (gethash uuid (yas/table-uuidhash table)))))
1431 (when yas/current-template
1432 (if yas/visit-from-menu
1433 (yas/visit-snippet-file-1 yas/current-template)
1434 (let ((where (if (region-active-p)
1435 (cons (region-beginning) (region-end))
1436 (cons (point) (point)))))
1437 (yas/expand-snippet (yas/template-content yas/current-template)
1440 (yas/template-expand-env yas/current-template)))))))
1442 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1443 ;; Popping up for keys and templates
1445 (defvar yas/x-pretty-prompt-templates nil
1446 "If non-nil, attempt to prompt for templates like TextMate.")
1449 (defun yas/prompt-for-template (templates &optional prompt)
1450 "Interactively choose a template from the list TEMPLATES.
1452 TEMPLATES is a list of `yas/template'."
1455 (sort templates #'(lambda (t1 t2)
1456 (< (length (yas/template-name t1))
1457 (length (yas/template-name t2))))))
1458 (if yas/x-pretty-prompt-templates
1459 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1460 (some #'(lambda (fn)
1461 (funcall fn (or prompt "Choose a snippet: ")
1463 #'yas/template-name))
1464 yas/prompt-functions))))
1466 (defun yas/prompt-for-keys (keys &optional prompt)
1467 "Interactively choose a template key from the list KEYS."
1469 (some #'(lambda (fn)
1470 (funcall fn (or prompt "Choose a snippet key: ") keys))
1471 yas/prompt-functions)))
1473 (defun yas/prompt-for-table (tables &optional prompt)
1475 (some #'(lambda (fn)
1476 (funcall fn (or prompt "Choose a snippet table: ")
1479 yas/prompt-functions)))
1481 (defun yas/x-prompt (prompt choices &optional display-fn)
1482 "Display choices in a x-window prompt."
1483 ;; FIXME: HACK: if we notice that one of the objects in choices is
1484 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1486 ;; This would be better implemented by passing CHOICES as a
1487 ;; strucutred tree rather than a list. Modifications would go as far
1488 ;; up as `yas/all-templates' I think.
1490 (when (and window-system choices)
1492 (let (menu d) ;; d for display
1494 (setq d (or (and display-fn (funcall display-fn c))
1497 (push (cons (concat " " d) c) menu))
1499 (push (car d) menu))))
1500 (setq menu (list prompt (push "title" menu)))
1501 (x-popup-menu (if (fboundp 'posn-at-point)
1502 (let ((x-y (posn-x-y (posn-at-point (point)))))
1503 (list (list (+ (car x-y) 10)
1511 (defun yas/x-pretty-prompt-templates (prompt templates)
1512 "Display TEMPLATES, grouping neatly by table name."
1513 (let ((organized (make-hash-table :test #'equal))
1517 (dolist (tl templates)
1518 (puthash (yas/template-table tl)
1520 (gethash (yas/template-table tl) organized))
1522 (setq more-than-one-table (> (hash-table-count organized) 1))
1523 (setq prefix (if more-than-one-table
1525 (if more-than-one-table
1526 (maphash #'(lambda (table templates)
1527 (push (yas/table-name table) menu)
1528 (dolist (tl templates)
1529 (push (cons (concat prefix (yas/template-name tl)) tl) menu))) organized)
1530 (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas/template-name tl)) tl)) templates)))
1532 (setq menu (nreverse menu))
1533 (or (x-popup-menu (if (fboundp 'posn-at-point)
1534 (let ((x-y (posn-x-y (posn-at-point (point)))))
1535 (list (list (+ (car x-y) 10)
1539 (list prompt (push "title" menu)))
1542 (defun yas/ido-prompt (prompt choices &optional display-fn)
1543 (when (fboundp 'ido-completing-read)
1544 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1546 (eval-when-compile (require 'dropdown-list nil t))
1547 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1548 (when (featurep 'dropdown-list)
1549 (let (formatted-choices
1553 (dolist (choice choices)
1554 (setq d (or (and display-fn (funcall display-fn choice))
1557 (push d formatted-choices)
1558 (push choice filtered-choices)))
1560 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1562 (nth n filtered-choices)
1565 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1566 (let (formatted-choices
1570 (completion-fn (or completion-fn
1571 #'completing-read)))
1572 (dolist (choice choices)
1573 (setq d (or (and display-fn (funcall display-fn choice))
1576 (push d formatted-choices)
1577 (push choice filtered-choices)))
1578 (setq chosen (and formatted-choices
1579 (funcall completion-fn prompt
1586 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1588 (defun yas/no-prompt (prompt choices &optional display-fn)
1591 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1592 ;; Loading snippets from files
1594 (defun yas/load-yas-setup-file (file)
1595 (load file 'noerror))
1597 (defun yas/load-directory (top-level-dir &optional use-jit)
1598 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1600 Below TOP-LEVEL-DIR each directory should be a mode name.
1602 Optional USE-JIT use jit-loading of snippets."
1603 (interactive "DSelect the root directory: ")
1604 (unless yas/snippet-dirs
1605 (setq yas/snippet-dirs top-level-dir))
1606 (dolist (dir (yas/subdirs top-level-dir))
1607 (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents
1608 (concat dir "/dummy")))
1609 (mode-sym (car major-mode-and-parents))
1610 (parents (cdr major-mode-and-parents)))
1611 (yas/define-parents mode-sym parents)
1612 (let ((form `(yas/load-directory-1 ,dir
1616 (yas/schedule-jit mode-sym form)
1618 (when (interactive-p)
1619 (yas/message 3 "Loaded snippets from %s." top-level-dir)))
1621 (defun yas/load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1622 "Recursively load snippet templates from DIRECTORY."
1623 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1624 (if (and (not no-compiled-snippets)
1625 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas/verbosity 2)))
1626 (yas/message 2 "Loading much faster .yas-compiled-snippets from %s" directory)
1627 (yas/load-directory-2 directory mode-sym))))
1629 (defun yas/load-directory-2 (directory mode-sym)
1630 ;; Load .yas-setup.el files wherever we find them
1632 (yas/load-yas-setup-file (expand-file-name ".yas-setup" directory))
1633 (let* ((default-directory directory)
1635 ;; load the snippet files
1638 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1639 (when (file-readable-p file)
1640 (insert-file-contents file nil nil nil t)
1641 (push (yas/parse-template file)
1644 (yas/define-snippets mode-sym
1646 ;; now recurse to a lower level
1648 (dolist (subdir (yas/subdirs directory))
1649 (yas/load-directory-2 subdir
1652 (defun yas/load-snippet-dirs (&optional nojit)
1653 "Reload the directories listed in `yas/snippet-dirs' or
1654 prompt the user to select one."
1656 (if yas/snippet-dirs
1657 (dolist (directory (reverse (yas/snippet-dirs)))
1658 (cond ((file-directory-p directory)
1659 (yas/load-directory directory (not nojit))
1660 (yas/message 3 "Loaded %s" directory))
1662 (push (yas/message 0 "Check your `yas/snippet-dirs': %s is not a directory" directory) errors))))
1663 (call-interactively 'yas/load-directory))
1666 (defun yas/reload-all (&optional interactive)
1667 "Reload all snippets and rebuild the YASnippet menu."
1671 (snippet-editing-buffers
1672 (remove-if-not #'(lambda (buffer)
1673 (with-current-buffer buffer yas/editing-template))
1675 ;; Warn if there are buffers visiting snippets, since reloading will break
1676 ;; any on-line editing of those buffers.
1678 (when snippet-editing-buffers
1680 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
1681 (mapcar #'kill-buffer snippet-editing-buffers)
1682 (yas/message 1 "Aborted reload...")
1684 ;; in a non-interactive use, at least set
1685 ;; `yas/editing-template' to nil, make it guess it next time around
1686 (mapc #'(lambda (buffer) (setq yas/editing-template nil)) (buffer-list))))
1688 ;; Empty all snippet tables, parenting info and all menu tables
1690 (setq yas/tables (make-hash-table))
1691 (setq yas/parents (make-hash-table))
1692 (setq yas/menu-table (make-hash-table))
1694 ;; Cancel all pending 'yas/scheduled-jit-loads'
1696 (setq yas/scheduled-jit-loads (make-hash-table))
1698 ;; Init the `yas/minor-mode-map', taking care not to break the
1701 (setf (cdr yas/minor-mode-map)
1702 (cdr (yas/init-minor-keymap)))
1704 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1705 ;; the user to select one.
1707 (setq errors (yas/load-snippet-dirs interactive))
1708 ;; Reload the direct keybindings
1710 (yas/direct-keymaps-reload)
1711 ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
1713 (yas/trigger-key-reload)
1715 (yas/message 3 "Reloaded everything...%s." (if errors " (some errors, check *Messages*)" "")))))
1717 (defun yas/load-pending-jits ()
1718 (when yas/minor-mode
1719 (dolist (mode (yas/modes-to-activate))
1720 (let ((forms (gethash mode yas/scheduled-jit-loads)))
1721 (dolist (form forms)
1722 (yas/message 3 "Loading snippets for %s, just in time: %s!" mode form)
1724 (remhash mode yas/scheduled-jit-loads)))))
1726 ;; (when (<= emacs-major-version 22)
1727 ;; (add-hook 'after-change-major-mode-hook 'yas/load-pending-jits))
1729 (defun yas/quote-string (string)
1730 "Escape and quote STRING.
1731 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1733 (replace-regexp-in-string "[\\\"]"
1738 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1739 ;;; Snippet compilation function
1741 (defun yas/initialize ()
1742 "For backward compatibility, enable `yas/minor-mode' globally"
1743 (yas/global-mode 1))
1745 (defun yas/compile-directory (top-level-dir)
1746 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1748 This works by stubbing a few functions, then calling
1749 `yas/load-directory'."
1750 (interactive "DTop level snippet directory?")
1751 (flet ((yas/load-yas-setup-file
1753 (let ((elfile (concat file ".el")))
1754 (when (file-exists-p elfile)
1755 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1756 (insert-file-contents elfile)
1759 (yas/define-snippets
1761 (insert ";;; Snippet definitions:\n;;;\n")
1762 (let ((literal-snippets (list))
1764 (dolist (snippet snippets)
1765 (let ((key (first snippet))
1766 (template-content (second snippet))
1767 (name (third snippet))
1768 (condition (fourth snippet))
1769 (group (fifth snippet))
1770 (expand-env (sixth snippet))
1771 (file nil) ;; (seventh snippet)) ;; omit on purpose
1772 (binding (eighth snippet))
1773 (uuid (ninth snippet)))
1784 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets)))
1786 (yas/load-directory-1
1787 (dir mode parents &rest ignore)
1788 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1789 (with-temp-file output-file
1790 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1791 (yas/load-directory-2 dir mode)
1792 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1793 (yas/load-directory top-level-dir nil)))
1795 (defun yas/recompile-all ()
1796 "Compile every dir in `yas/snippet-dirs'."
1798 (mapc #'yas/compile-directory (yas/snippet-dirs)))
1804 (defvar yas/scheduled-jit-loads (make-hash-table)
1805 "Alist of mode-symbols to forms to be evaled when `yas/minor-mode' kicks in.")
1807 (defun yas/schedule-jit (mode form)
1810 (gethash mode yas/scheduled-jit-loads))
1811 yas/scheduled-jit-loads))
1814 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1815 ;;; Some user level functions
1820 (message (concat "yasnippet (version "
1822 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1824 (defun yas/define-parents (mode parents)
1825 "Add PARENTS to the list of MODE's parents"
1826 (puthash mode-sym (remove-duplicates
1828 (gethash mode-sym yas/parents)))
1831 (defun yas/define-snippets (mode snippets)
1832 "Define SNIPPETS for MODE.
1834 SNIPPETS is a list of snippet definitions, each taking the
1837 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1839 Within these, only KEY and TEMPLATE are actually mandatory.
1841 TEMPLATE might be a lisp form or a string, depending on whether
1842 this is a snippet or a snippet-command.
1844 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1845 been `yas/read-lisp'-ed and will eventually be
1848 The remaining elements are strings.
1850 FILE is probably of very little use if you're programatically
1853 UUID is the snippets \"unique-id\". Loading a second snippet file
1854 with the same uuid replaced the previous snippet.
1856 You can use `yas/parse-template' to return such lists based on
1857 the current buffers contents."
1858 (let ((snippet-table (yas/table-get-create mode))
1860 (dolist (snippet snippets)
1861 (setq template (yas/define-snippets-1 snippet
1865 (defun yas/define-snippets-1 (snippet snippet-table)
1866 "Helper for `yas/define-snippets'."
1867 ;; X) Calculate some more defaults on the values returned by
1868 ;; `yas/parse-template'.
1870 (let* ((file (seventh snippet))
1872 (name (or (third snippet)
1874 (file-name-directory file))))
1875 (condition (fourth snippet))
1876 (group (fifth snippet))
1877 (keybinding (yas/read-keybinding (eighth snippet)))
1878 (uuid (or (ninth snippet)
1880 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1881 (yas/make-blank-template))))
1882 ;; X) populate the template object
1884 (yas/populate-template template
1885 :table snippet-table
1887 :content (second snippet)
1890 :condition condition
1891 :expand-env (sixth snippet)
1892 :file (seventh snippet)
1893 :keybinding keybinding
1895 ;; X) Update this template in the appropriate table. This step
1896 ;; also will take care of adding the key indicators in the
1897 ;; templates menu entry, if any
1899 (yas/update-template snippet-table template)
1900 ;; X) Return the template
1905 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1906 "Get TEMPLATE's menu binding or assign it a new one.
1908 TYPE may be `:stay', signalling this menu binding should be
1909 static in the menu."
1910 (or (yas/template-menu-binding-pair template)
1911 (let ((key (yas/template-key template))
1912 (keybinding (yas/template-keybinding template)))
1913 (setf (yas/template-menu-binding-pair template)
1914 (cons `(menu-item ,(or (yas/template-name template)
1915 (yas/template-uuid template))
1916 ,(yas/make-menu-binding template)
1920 (defun yas/show-menu-p (mode)
1921 (cond ((eq yas/use-menu 'abbreviate)
1923 (mapcar #'(lambda (table)
1924 (intern (yas/table-name table)))
1925 (yas/get-snippet-tables))))
1926 ((eq yas/use-menu 'real-modes)
1927 (yas/real-mode? mode))
1931 (defun yas/delete-from-keymap (keymap uuid)
1932 "Recursively delete items with UUID from KEYMAP and its submenus."
1934 ;; XXX: This used to skip any submenus named \"parent mode\"
1936 ;; First of all, recursively enter submenus, i.e. the tree is
1937 ;; searched depth first so that stale submenus can be found in the
1940 (mapc #'(lambda (item)
1941 (when (and (listp (cdr item))
1942 (keymapp (third (cdr item))))
1943 (yas/delete-from-keymap (third (cdr item)) uuid)))
1945 ;; Set the uuid entry to nil
1947 (define-key keymap (vector (make-symbol uuid)) nil)
1948 ;; Destructively modify keymap
1950 (setcdr keymap (delete-if #'(lambda (item)
1951 (or (null (cdr item))
1952 (and (keymapp (third (cdr item)))
1953 (null (cdr (third (cdr item)))))))
1956 (defun yas/define-menu (mode menu omit-items)
1957 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
1959 MENU is a list, its elements can be:
1961 - (yas/item UUID) : Creates an entry the snippet identified with
1962 UUID. The menu entry for a snippet thus identified is
1963 permanent, i.e. it will never move (be reordered) in the menu.
1965 - (yas/separator) : Creates a separator
1967 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
1968 SUBMENU has the same form as MENU. NAME is also added to the
1969 list of groups of the snippets defined thereafter.
1971 OMIT-ITEMS is a list of snippet uuid's that will always be
1972 ommited from MODE's menu, even if they're manually loaded.
1974 (let* ((table (yas/table-get-create mode))
1975 (hash (yas/table-uuidhash table)))
1976 (yas/define-menu-1 table
1977 (yas/menu-keymap-get-create table)
1980 (dolist (uuid omit-items)
1981 (let ((template (or (gethash uuid hash)
1982 (yas/populate-template (puthash uuid
1983 (yas/make-blank-template)
1987 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
1989 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
1990 (dolist (e (reverse menu))
1991 (cond ((eq (first e) 'yas/item)
1992 (let ((template (or (gethash (second e) uuidhash)
1993 (yas/populate-template (puthash (second e)
1994 (yas/make-blank-template)
1997 :perm-group group-list
1998 :uuid (second e)))))
1999 (define-key keymap (vector (gensym))
2000 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2001 ((eq (first e) 'yas/submenu)
2002 (let ((subkeymap (make-sparse-keymap)))
2003 (define-key keymap (vector (gensym))
2004 `(menu-item ,(second e) ,subkeymap))
2005 (yas/define-menu-1 table
2009 (append group-list (list (second e))))))
2010 ((eq (first e) 'yas/separator)
2011 (define-key keymap (vector (gensym))
2012 '(menu-item "----")))
2014 (yas/message 3 "Don't know anything about menu entry %s" (first e))))))
2016 (defun yas/define (mode key template &optional name condition group)
2017 "Define a snippet. Expanding KEY into TEMPLATE.
2019 NAME is a description to this template. Also update the menu if
2020 `yas/use-menu' is `t'. CONDITION is the condition attached to
2021 this snippet. If you attach a condition to a snippet, then it
2022 will only be expanded when the condition evaluated to non-nil."
2023 (yas/define-snippets mode
2024 (list (list key template name condition group))))
2026 (defun yas/hippie-try-expand (first-time?)
2027 "Integrate with hippie expand. Just put this function in
2028 `hippie-expand-try-functions-list'."
2029 (if (not first-time?)
2030 (let ((yas/fallback-behavior 'return-nil))
2036 ;;; Apropos condition-cache:
2041 (defvar yas/condition-cache-timestamp nil)
2042 (defmacro yas/define-condition-cache (func doc &rest body)
2043 "Define a function FUNC with doc DOC and body BODY, BODY is
2044 executed at most once every snippet expansion attempt, to check
2045 expansion conditions.
2047 It doesn't make any sense to call FUNC programatically."
2048 `(defun ,func () ,(if (and doc
2051 "\n\nFor use in snippets' conditions. Within each
2052 snippet-expansion routine like `yas/expand', computes actual
2053 value for the first time then always returns a cached value.")
2054 (setq body (cons doc body))
2056 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2057 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2058 (cdr timestamp-and-value)
2059 (let ((new-value (progn
2062 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2065 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2066 (defun yas/expand-from-trigger-key (&optional field)
2067 "Expand a snippet before point.
2069 If no snippet expansion is possible, fall back to the behaviour
2070 defined in `yas/fallback-behavior'.
2072 Optional argument FIELD is for non-interactive use and is an
2073 object satisfying `yas/field-p' to restrict the expansion to."
2075 (setq yas/condition-cache-timestamp (current-time))
2076 (let (templates-and-pos)
2077 (unless (and yas/expand-only-for-last-commands
2078 (not (member last-command yas/expand-only-for-last-commands)))
2079 (setq templates-and-pos (if field
2081 (narrow-to-region (yas/field-start field)
2082 (yas/field-end field))
2084 (yas/current-key))))
2085 (if (and templates-and-pos
2086 (first templates-and-pos))
2087 (yas/expand-or-prompt-for-template (first templates-and-pos)
2088 (second templates-and-pos)
2089 (third templates-and-pos))
2090 (yas/fallback 'trigger-key))))
2092 (defun yas/expand-from-keymap ()
2093 "Directly expand some snippets, searching `yas/direct-keymaps'.
2095 If expansion fails, execute the previous binding for this key"
2097 (setq yas/condition-cache-timestamp (current-time))
2098 (let* ((yas/prefix current-prefix-arg)
2099 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2100 universal-argument-num-events
2102 (templates (mapcan #'(lambda (table)
2103 (yas/fetch table vec))
2104 (yas/get-snippet-tables))))
2106 (yas/expand-or-prompt-for-template templates)
2107 (let ((yas/fallback-behavior 'call-other-command))
2110 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2111 "Expand one of TEMPLATES from START to END.
2113 Prompt the user if TEMPLATES has more than one element, else
2114 expand immediately. Common gateway for
2115 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2116 (let ((yas/current-template (or (and (rest templates) ;; more than one
2117 (yas/prompt-for-template (mapcar #'cdr templates)))
2119 (when yas/current-template
2120 (yas/expand-snippet (yas/template-content yas/current-template)
2123 (yas/template-expand-env yas/current-template)))))
2125 (defun yas/fallback (&optional from-trigger-key-p)
2126 "Fallback after expansion has failed.
2128 Common gateway for `yas/expand-from-trigger-key' and
2129 `yas/expand-from-keymap'."
2130 (cond ((eq yas/fallback-behavior 'return-nil)
2133 ((eq yas/fallback-behavior 'call-other-command)
2134 (let* ((yas/minor-mode nil)
2135 (yas/direct-keymaps nil)
2136 (keys-1 (this-command-keys-vector))
2137 (keys-2 (and yas/trigger-key
2139 (stringp yas/trigger-key)
2140 (read-kbd-macro yas/trigger-key)))
2141 (command-1 (and keys-1 (key-binding keys-1)))
2142 (command-2 (and keys-2 (key-binding keys-2)))
2143 ;; An (ugly) safety: prevents infinite recursion of
2144 ;; yas/expand* calls.
2145 (command (or (and (symbolp command-1)
2146 (not (string-match "yas/expand" (symbol-name command-1)))
2148 (and (symbolp command-2)
2150 (when (and (commandp command)
2151 (not (string-match "yas/expand" (symbol-name command))))
2152 (setq this-command command)
2153 (call-interactively command))))
2154 ((and (listp yas/fallback-behavior)
2155 (cdr yas/fallback-behavior)
2156 (eq 'apply (car yas/fallback-behavior)))
2157 (if (cddr yas/fallback-behavior)
2158 (apply (cadr yas/fallback-behavior)
2159 (cddr yas/fallback-behavior))
2160 (when (commandp (cadr yas/fallback-behavior))
2161 (setq this-command (cadr yas/fallback-behavior))
2162 (call-interactively (cadr yas/fallback-behavior)))))
2164 ;; also return nil if all the other fallbacks have failed
2169 ;;; Snippet development
2171 (defun yas/all-templates (tables)
2172 "Return all snippet tables applicable for the current buffer.
2174 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2175 `yas/buffer-local-condition'"
2176 (when yas/choose-tables-first
2177 (setq tables (list (yas/prompt-for-table tables))))
2179 (if yas/choose-keys-first
2180 (let ((key (yas/prompt-for-keys
2181 (mapcan #'yas/table-all-keys tables))))
2183 (mapcan #'(lambda (table)
2184 (yas/fetch table key))
2186 (remove-duplicates (mapcan #'yas/table-templates tables)
2189 (defun yas/insert-snippet (&optional no-condition)
2190 "Choose a snippet to expand, pop-up a list of choices according
2191 to `yas/prompt-function'.
2193 With prefix argument NO-CONDITION, bypass filtering of snippets
2196 (setq yas/condition-cache-timestamp (current-time))
2197 (let* ((yas/buffer-local-condition (or (and no-condition
2199 yas/buffer-local-condition))
2200 (templates (yas/all-templates (yas/get-snippet-tables)))
2201 (yas/current-template (and templates
2202 (or (and (rest templates) ;; more than one template for same key
2203 (yas/prompt-for-template templates))
2205 (where (if (region-active-p)
2206 (cons (region-beginning) (region-end))
2207 (cons (point) (point)))))
2208 (if yas/current-template
2209 (yas/expand-snippet (yas/template-content yas/current-template)
2212 (yas/template-expand-env yas/current-template))
2213 (yas/message 3 "No snippets can be inserted here!"))))
2215 (defun yas/visit-snippet-file ()
2216 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2218 Only success if selected snippet was loaded from a file. Put the
2219 visited file in `snippet-mode'."
2221 (let* ((yas/buffer-local-condition 'always)
2222 (templates (yas/all-templates (yas/get-snippet-tables)))
2223 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2224 (template (and templates
2225 (or (yas/prompt-for-template templates
2226 "Choose a snippet template to edit: ")
2230 (yas/visit-snippet-file-1 template)
2231 (message "No snippets tables active!"))))
2233 (defun yas/visit-snippet-file-1 (template)
2234 (let ((file (yas/template-file template)))
2235 (cond ((and file (file-readable-p file))
2236 (find-file-other-window file)
2238 (set (make-local-variable 'yas/editing-template) template))
2240 (message "Original file %s no longer exists!" file))
2242 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2243 (let ((type 'snippet))
2244 (when (listp (yas/template-content template))
2245 (insert (format "# type: command\n"))
2246 (setq type 'command))
2247 (insert (format "# key: %s\n" (yas/template-key template)))
2248 (insert (format "# name: %s\n" (yas/template-name template)))
2249 (when (yas/template-keybinding template)
2250 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2251 (when (yas/template-expand-env template)
2252 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2253 (when (yas/template-condition template)
2254 (insert (format "# condition: %s\n" (yas/template-condition template))))
2256 (insert (if (eq type 'command)
2257 (pp-to-string (yas/template-content template))
2258 (yas/template-content template))))
2260 (set (make-local-variable 'yas/editing-template) template)))))
2262 (defun yas/guess-snippet-directories-1 (table)
2263 "Guesses possible snippet subdirectories for TABLE."
2264 (cons (yas/table-name table)
2265 (mapcan #'(lambda (parent)
2266 (yas/guess-snippet-directories-1
2268 (yas/table-parents table))))
2270 (defun yas/guess-snippet-directories (&optional table)
2271 "Try to guess suitable directories based on the current active
2272 tables (or optional TABLE).
2274 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2275 `yas/table' object and DIRS is a list of all possible directories
2276 where snippets of table might exist."
2277 (let ((main-dir (replace-regexp-in-string
2279 (or (first (or (yas/snippet-dirs)
2280 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2281 (tables (or (and table
2283 (yas/get-snippet-tables))))
2284 ;; HACK! the snippet table created here is actually registered!
2286 (unless (or table (gethash major-mode yas/tables))
2287 (push (yas/table-get-create major-mode)
2290 (mapcar #'(lambda (table)
2292 (mapcar #'(lambda (subdir)
2293 (concat main-dir "/" subdir))
2294 (yas/guess-snippet-directories-1 table))))
2297 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2298 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2299 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2300 (let ((candidate (first (cdr table-and-dirs))))
2301 (unless (file-writable-p (file-name-directory candidate))
2302 (error (yas/format "%s is not writable." candidate)))
2303 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2305 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2309 (or main-table-string
2311 (yas/table-name (car table-and-dirs))))
2313 (make-directory candidate 'also-make-parents)
2314 ;; create the .yas-parents file here...
2317 (defun yas/new-snippet (&optional no-template)
2318 "Pops a new buffer for writing a snippet.
2320 Expands a snippet-writing snippet, unless the optional prefix arg
2321 NO-TEMPLATE is non-nil."
2323 (let ((guessed-directories (yas/guess-snippet-directories)))
2325 (switch-to-buffer "*new snippet*")
2327 (kill-all-local-variables)
2330 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2331 (intern (yas/table-name (car d))))
2332 guessed-directories))
2333 (unless no-template (yas/expand-snippet "\
2334 # -*- mode: snippet -*-
2336 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas/text)}}${3:
2337 # binding: ${4:direct-keybinding}}${5:
2338 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2343 (defun yas/compute-major-mode-and-parents (file)
2344 "Given FILE, find the nearest snippet directory for a given
2345 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2346 representing one or more of the mode's parents.
2348 Note that MODE-SYM need not be the symbol of a real major mode,
2349 neither do the elements of PARENTS."
2350 (let* ((file-dir (and file
2351 (directory-file-name (or (some #'(lambda (special)
2352 (locate-dominating-file file special))
2356 (directory-file-name (file-name-directory file))))))
2357 (parents-file-name (concat file-dir "/.yas-parents"))
2358 (major-mode-name (and file-dir
2359 (file-name-nondirectory file-dir)))
2360 (major-mode-sym (or (and major-mode-name
2361 (intern major-mode-name))))
2362 (parents (when (file-readable-p parents-file-name)
2366 (insert-file-contents parents-file-name)
2367 (buffer-substring-no-properties (point-min)
2369 (when major-mode-sym
2370 (cons major-mode-sym parents))))
2372 (defvar yas/editing-template nil
2373 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2375 (defvar yas/current-template nil
2376 "Holds the current template being expanded into a snippet.")
2378 (defvar yas/guessed-modes nil
2379 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2381 (defun yas/load-snippet-buffer (&optional kill)
2382 "Parse and load current buffer's snippet definition.
2384 With optional prefix argument KILL quit the window and buffer."
2387 ;; We have `yas/editing-template', this buffer's
2388 ;; content comes from a template which is already loaded and
2389 ;; neatly positioned,...
2391 (yas/editing-template
2392 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2393 (yas/template-table yas/editing-template)))
2394 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2395 ;; value from `yas/compute-major-mode-and-parents'
2398 (unless yas/guessed-modes
2399 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2400 (let* ((prompt (if (and (featurep 'ido)
2402 'ido-completing-read 'completing-read))
2403 (table (yas/table-get-create
2405 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2406 (if yas/guessed-modes
2407 (first yas/guessed-modes)
2409 (mapcar #'symbol-name yas/guessed-modes)
2414 (if (first yas/guessed-modes)
2415 (symbol-name (first yas/guessed-modes))))))))
2416 (set (make-local-variable 'yas/editing-template)
2417 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2419 ;; Now, offer to save this shit iff:
2421 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2422 ;; match this template's file (i.e. this is a library snippet, not
2423 ;; a user snippet) OR
2425 ;; 2) yas/editing-template comes from a file that we cannot write to...
2427 (when (or (not (yas/template-file yas/editing-template))
2428 (not (file-writable-p (yas/template-file yas/editing-template)))
2429 (and (listp yas/snippet-dirs)
2430 (second yas/snippet-dirs)
2431 (not (string-match (expand-file-name (first yas/snippet-dirs))
2432 (yas/template-file yas/editing-template)))))
2434 (when (y-or-n-p (yas/format "Looks like a library or new snippet. Save to new file? "))
2435 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2437 (yas/make-directory-maybe option))))
2439 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2440 (file-name-nondirectory (yas/template-file yas/editing-template)))
2441 (yas/template-name yas/editing-template))))
2442 (write-file (concat chosen "/"
2443 (read-from-minibuffer (format "File name to create in %s? " chosen)
2444 default-file-name)))
2445 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2448 (yas/message 3 "Snippet \"%s\" loaded for %s."
2449 (yas/template-name yas/editing-template)
2450 (yas/table-name (yas/template-table yas/editing-template))))
2453 (defun yas/tryout-snippet (&optional debug)
2454 "Test current buffers's snippet template in other buffer."
2456 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2457 (parsed (yas/parse-template))
2458 (test-mode (or (and (car major-mode-and-parent)
2459 (fboundp (car major-mode-and-parent))
2460 (car major-mode-and-parent))
2461 (first yas/guessed-modes)
2462 (intern (read-from-minibuffer (yas/format "Please input a mode: ")))))
2463 (yas/current-template
2466 (yas/populate-template (yas/make-blank-template)
2467 :table nil ;; no tables for ephemeral snippets
2469 :content (second parsed)
2470 :name (third parsed)
2471 :expand-env (sixth parsed)))))
2472 (cond (yas/current-template
2473 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2474 (kill-buffer (get-buffer-create buffer-name))
2475 (switch-to-buffer (get-buffer-create buffer-name))
2476 (setq buffer-undo-list nil)
2477 (condition-case nil (funcall test-mode) (error nil))
2478 (setq buffer-read-only nil)
2479 (yas/expand-snippet (yas/template-content yas/current-template)
2482 (yas/template-expand-env yas/current-template))
2484 (require 'yasnippet-debug nil t))
2485 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2487 (yas/message 3 "Cannot test snippet for unknown major mode")))))
2489 (defun yas/template-fine-group (template)
2490 (car (last (or (yas/template-group template)
2491 (yas/template-perm-group template)))))
2493 (defun yas/describe-tables (&optional choose)
2494 "Display snippets for each table."
2496 (let* ((by-name-hash (and choose
2497 (y-or-n-p "Show by namehash? ")))
2498 (buffer (get-buffer-create "*YASnippet tables*"))
2499 (active-tables (yas/get-snippet-tables))
2500 (remain-tables (let ((all))
2501 (maphash #'(lambda (k v)
2502 (unless (find v active-tables)
2506 (table-lists (list active-tables remain-tables))
2507 (original-buffer (current-buffer))
2509 (yas/condition-cache-timestamp (current-time)))
2510 (with-current-buffer buffer
2511 (setq buffer-read-only nil)
2513 (cond ((not by-name-hash)
2514 (insert "YASnippet tables: \n")
2515 (while (and table-lists
2517 (dolist (table (car table-lists))
2518 (yas/describe-pretty-table table original-buffer))
2519 (setq table-lists (cdr table-lists))
2521 (yas/create-snippet-xrefs)
2522 (display-buffer buffer)
2523 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2524 (yas/create-snippet-xrefs)
2528 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2529 (dolist (table (append active-tables remain-tables))
2530 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2532 (maphash #'(lambda (k v)
2534 (yas/table-hash table))
2536 (insert (format " key %s maps snippets: %s\n" key
2538 (maphash #'(lambda (k v)
2540 (gethash key (yas/table-hash table)))
2543 (setq buffer-read-only t))
2544 (display-buffer buffer)))
2546 (defun yas/describe-pretty-table (table &optional original-buffer)
2547 (insert (format "\nSnippet table `%s'"
2548 (yas/table-name table)))
2549 (if (yas/table-parents table)
2550 (insert (format " parents: %s\n"
2551 (mapcar #'yas/table-name
2552 (yas/table-parents table))))
2554 (insert (make-string 100 ?-) "\n")
2555 (insert "group state name key binding\n")
2556 (let ((groups-hash (make-hash-table :test #'equal)))
2557 (maphash #'(lambda (k v)
2558 (let ((group (or (yas/template-fine-group v)
2560 (when (yas/template-name v)
2562 (cons v (gethash group groups-hash))
2564 (yas/table-uuidhash table))
2566 #'(lambda (group templates)
2567 (setq group (truncate-string-to-width group 25 0 ? "..."))
2568 (insert (make-string 100 ?-) "\n")
2569 (dolist (p templates)
2570 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2574 (setq group (make-string (length group) ? ))))
2575 (condition-string (let ((condition (yas/template-condition p)))
2578 (with-current-buffer original-buffer
2579 (if (yas/eval-condition condition)
2584 (insert condition-string " ")
2586 (if (string-match "\\.\\.\\.$" name)
2590 (insert (truncate-string-to-width (or (yas/template-key p) "")
2592 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2599 ;;; User convenience functions, for using in snippet definitions
2601 (defvar yas/modified-p nil
2602 "Non-nil if field has been modified by user or transformation.")
2604 (defvar yas/moving-away-p nil
2605 "Non-nil if user is about to exit field.")
2607 (defvar yas/text nil
2608 "Contains current field text.")
2610 (defun yas/substr (str pattern &optional subexp)
2611 "Search PATTERN in STR and return SUBEXPth match.
2613 If found, the content of subexp group SUBEXP (default 0) is
2614 returned, or else the original STR will be returned."
2615 (let ((grp (or subexp 0)))
2617 (if (string-match pattern str)
2618 (match-string-no-properties grp str)
2621 (defun yas/choose-value (possibilities)
2622 "Prompt for a string in the list POSSIBILITIES and return it."
2623 (unless (or yas/moving-away-p
2625 (some #'(lambda (fn)
2626 (funcall fn "Choose: " possibilities))
2627 yas/prompt-functions)))
2629 (defun yas/key-to-value (alist)
2630 "Prompt for a string in the list POSSIBILITIES and return it."
2631 (unless (or yas/moving-away-p
2633 (let ((key (read-key-sequence "")))
2635 (or (cdr (find key alist :key #'car :test #'string=))
2638 (defun yas/throw (text)
2639 "Throw a yas/exception with TEXT as the reason."
2640 (throw 'yas/exception (cons 'yas/exception text)))
2642 (defun yas/verify-value (possibilities)
2643 "Verify that the current field value is in POSSIBILITIES
2645 Otherwise throw exception."
2646 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2647 (yas/throw (yas/format "Field only allows %s" possibilities))))
2649 (defun yas/field-value (number)
2650 "Get the string for field with NUMBER.
2652 Use this in primary and mirror transformations to tget."
2653 (let* ((snippet (car (yas/snippets-at-point)))
2655 (yas/snippet-find-field snippet number))))
2657 (yas/field-text-for-display field))))
2660 "Return `yas/text' if that exists and is non-empty, else nil."
2662 (not (string= "" yas/text)))
2665 ;; (defun yas/selected-text ()
2666 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2667 ;; (if (and yas/selected-text
2668 ;; (not (string= "" yas/selected-text)))
2669 ;; yas/selected-text))
2671 (defun yas/get-field-once (number &optional transform-fn)
2672 (unless yas/modified-p
2674 (funcall transform-fn (yas/field-value number))
2675 (yas/field-value number))))
2677 (defun yas/default-from-field (number)
2678 (unless yas/modified-p
2679 (yas/field-value number)))
2681 (defun yas/inside-string ()
2682 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2684 (defun yas/unimplemented (&optional missing-feature)
2685 (if yas/current-template
2686 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2689 (yas/visit-snippet-file-1 yas/current-template))
2690 (message "No implementation. Missing %s" (or missing-feature "something"))))
2693 ;;; Snippet expansion and field management
2695 (defvar yas/active-field-overlay nil
2696 "Overlays the currently active field.")
2698 (defvar yas/field-protection-overlays nil
2699 "Two overlays protect the current active field ")
2701 (defconst yas/prefix nil
2702 "A prefix argument for expansion direct from keybindings")
2704 (defvar yas/selected-text nil
2705 "The selected region deleted on the last snippet expansion.")
2707 (defvar yas/start-column nil
2708 "The column where the snippet expansion started.")
2710 (make-variable-buffer-local 'yas/active-field-overlay)
2711 (make-variable-buffer-local 'yas/field-protection-overlays)
2712 (put 'yas/active-field-overlay 'permanent-local t)
2713 (put 'yas/field-protection-overlays 'permanent-local t)
2715 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2721 (id (yas/snippet-next-id) :read-only t)
2722 (control-overlay nil)
2724 ;; stacked expansion: the `previous-active-field' slot saves the
2725 ;; active field where the child expansion took place
2726 previous-active-field
2729 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2739 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2746 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2750 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2751 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2753 If there is no transform for ht field, return nil.
2755 If there is a transform but it returns nil, return the empty
2756 string iff EMPTY-ON-NIL-P is true."
2757 (let* ((yas/text (yas/field-text-for-display field))
2759 (yas/modified-p (yas/field-modified-p field))
2760 (yas/moving-away-p nil)
2761 (transform (if (yas/mirror-p field-or-mirror)
2762 (yas/mirror-transform field-or-mirror)
2763 (yas/field-transform field-or-mirror)))
2764 (start-point (if (yas/mirror-p field-or-mirror)
2765 (yas/mirror-start field-or-mirror)
2766 (yas/field-start field-or-mirror)))
2767 (transformed (and transform
2769 (goto-char start-point)
2770 (let ((ret (yas/eval-lisp transform)))
2771 (or ret (and empty-on-nil-p "")))))))
2774 (defsubst yas/replace-all (from to &optional text)
2775 "Replace all occurance from FROM to TO.
2777 With optional string TEXT do it in that string."
2779 (replace-regexp-in-string (regexp-quote from) to text t t)
2780 (goto-char (point-min))
2781 (while (search-forward from nil t)
2782 (replace-match to t t text))))
2784 (defun yas/snippet-find-field (snippet number)
2785 (find-if #'(lambda (field)
2786 (eq number (yas/field-number field)))
2787 (yas/snippet-fields snippet)))
2789 (defun yas/snippet-sort-fields (snippet)
2790 "Sort the fields of SNIPPET in navigation order."
2791 (setf (yas/snippet-fields snippet)
2792 (sort (yas/snippet-fields snippet)
2793 #'yas/snippet-field-compare)))
2795 (defun yas/snippet-field-compare (field1 field2)
2796 "Compare two fields. The field with a number is sorted first.
2797 If they both have a number, compare through the number. If neither
2798 have, compare through the field's start point"
2799 (let ((n1 (yas/field-number field1))
2800 (n2 (yas/field-number field2)))
2803 (or (zerop n2) (and (not (zerop n1))
2808 (< (yas/field-start field1)
2809 (yas/field-start field2))))))
2811 (defun yas/field-probably-deleted-p (snippet field)
2812 "Guess if SNIPPET's FIELD should be skipped."
2814 ;; field must be zero lentgh
2816 (zerop (- (yas/field-start field) (yas/field-end field)))
2819 ;; 1) is a nested field and it's been modified
2821 (and (yas/field-parent-field field)
2822 (yas/field-modified-p field))
2823 ;; 2) ends just before the snippet end
2825 (and (eq field (car (last (yas/snippet-fields snippet))))
2826 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2827 ;; the field numbered 0, just before the exit marker, should
2830 (not (zerop (yas/field-number field)))))
2832 (defun yas/snippets-at-point (&optional all-snippets)
2833 "Return a sorted list of snippets at point, most recently
2836 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2837 (overlay-get ov 'yas/snippet))
2839 (overlays-in (point-min) (point-max))
2840 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2842 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2844 (defun yas/next-field-or-maybe-expand ()
2845 "Try to expand a snippet at a key before point, otherwise
2846 delegate to `yas/next-field'."
2848 (if yas/triggers-in-field
2849 (let ((yas/fallback-behavior 'return-nil)
2850 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2852 (unless (yas/expand-from-trigger-key active-field)
2856 (defun yas/next-field (&optional arg)
2857 "Navigate to next field. If there's none, exit the snippet."
2861 (snippet (first (yas/snippets-at-point)))
2862 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2863 (live-fields (remove-if #'(lambda (field)
2864 (and (not (eq field active-field))
2865 (yas/field-probably-deleted-p snippet field)))
2866 (yas/snippet-fields snippet)))
2867 (active-field-pos (position active-field live-fields))
2868 (target-pos (and active-field-pos (+ arg active-field-pos)))
2869 (target-field (and target-pos (nth target-pos live-fields))))
2870 ;; First check if we're moving out of a field with a transform
2872 (when (and active-field
2873 (yas/field-transform active-field))
2874 (let* ((yas/moving-away-p t)
2875 (yas/text (yas/field-text-for-display active-field))
2877 (yas/modified-p (yas/field-modified-p active-field)))
2878 ;; primary field transform: exit call to field-transform
2879 (yas/eval-lisp (yas/field-transform active-field))))
2880 ;; Now actually move...
2881 (cond ((and target-pos (>= target-pos (length live-fields)))
2882 (yas/exit-snippet snippet))
2884 (yas/move-to-field snippet target-field))
2888 (defun yas/place-overlays (snippet field)
2889 "Correctly place overlays for SNIPPET's FIELD"
2890 (yas/make-move-field-protection-overlays snippet field)
2891 (yas/make-move-active-field-overlay snippet field))
2893 (defun yas/move-to-field (snippet field)
2894 "Update SNIPPET to move to field FIELD.
2896 Also create some protection overlays"
2897 (goto-char (yas/field-start field))
2898 (yas/place-overlays snippet field)
2899 (overlay-put yas/active-field-overlay 'yas/field field)
2900 (let ((number (yas/field-number field)))
2901 ;; check for the special ${0: ...} field
2902 (if (and number (zerop number))
2904 (set-mark (yas/field-end field))
2905 (setf (yas/snippet-force-exit snippet)
2906 (or (yas/field-transform field)
2908 ;; make this field active
2909 (setf (yas/snippet-active-field snippet) field)
2910 ;; primary field transform: first call to snippet transform
2911 (unless (yas/field-modified-p field)
2912 (if (yas/field-update-display field snippet)
2913 (yas/update-mirrors snippet)
2914 (setf (yas/field-modified-p field) nil))))))
2916 (defun yas/prev-field ()
2917 "Navigate to prev field. If there's none, exit the snippet."
2919 (yas/next-field -1))
2921 (defun yas/abort-snippet (&optional snippet)
2923 (let ((snippet (or snippet
2924 (car (yas/snippets-at-point)))))
2926 (setf (yas/snippet-force-exit snippet) t))))
2928 (defun yas/exit-snippet (snippet)
2929 "Goto exit-marker of SNIPPET."
2930 (interactive (list (first (yas/snippets-at-point))))
2932 (setf (yas/snippet-force-exit snippet) t)
2933 (goto-char (if (yas/snippet-exit snippet)
2934 (yas/exit-marker (yas/snippet-exit snippet))
2935 (overlay-end (yas/snippet-control-overlay snippet))))))
2937 (defun yas/exit-all-snippets ()
2938 "Exit all snippets."
2940 (mapc #'(lambda (snippet)
2941 (yas/exit-snippet snippet)
2942 (yas/check-commit-snippet))
2943 (yas/snippets-at-point 'all-snippets)))
2946 ;;; Some low level snippet-routines
2948 (defmacro yas/inhibit-overlay-hooks (&rest body)
2949 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
2950 (declare (indent 0))
2951 `(let ((yas/inhibit-overlay-hooks t))
2954 (defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
2955 (defvar yas/snippet-end nil "End position of the last snippet commited.")
2957 (defun yas/commit-snippet (snippet)
2958 "Commit SNIPPET, but leave point as it is. This renders the
2959 snippet as ordinary text."
2961 (let ((control-overlay (yas/snippet-control-overlay snippet)))
2963 ;; Save the end of the moribund snippet in case we need to revive it
2964 ;; its original expansion.
2966 (when (and control-overlay
2967 (overlay-buffer control-overlay))
2968 (setq yas/snippet-beg (overlay-start control-overlay))
2969 (setq yas/snippet-end (overlay-end control-overlay))
2970 (delete-overlay control-overlay))
2972 (yas/inhibit-overlay-hooks
2973 (when yas/active-field-overlay
2974 (delete-overlay yas/active-field-overlay))
2975 (when yas/field-protection-overlays
2976 (mapc #'delete-overlay yas/field-protection-overlays)))
2978 ;; stacked expansion: if the original expansion took place from a
2979 ;; field, make sure we advance it here at least to
2980 ;; `yas/snippet-end'...
2982 (let ((previous-field (yas/snippet-previous-active-field snippet)))
2983 (when (and yas/snippet-end previous-field)
2984 (yas/advance-end-maybe previous-field yas/snippet-end)))
2986 ;; Convert all markers to points,
2988 (yas/markers-to-points snippet)
2990 ;; Take care of snippet revival
2992 (if yas/snippet-revival
2993 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
2995 ;; Dismember the snippet... this is useful if we get called
2996 ;; again from `yas/take-care-of-redo'....
2997 (setf (yas/snippet-fields snippet) nil)))
2999 (yas/message 3 "Snippet %s exited." (yas/snippet-id snippet)))
3001 (defun yas/safely-run-hooks (hook-var)
3002 (condition-case error
3003 (run-hooks hook-var)
3005 (yas/message 3 "%s error: %s" hook-var (error-message-string error)))))
3008 (defun yas/check-commit-snippet ()
3009 "Checks if point exited the currently active field of the
3010 snippet, if so cleans up the whole snippet up."
3011 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3012 (snippets-left snippets)
3013 (snippet-exit-transform))
3014 (dolist (snippet snippets)
3015 (let ((active-field (yas/snippet-active-field snippet)))
3016 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3017 (cond ((or snippet-exit-transform
3018 (not (and active-field (yas/field-contains-point-p active-field))))
3019 (setq snippets-left (delete snippet snippets-left))
3020 (setf (yas/snippet-force-exit snippet) nil)
3021 (yas/commit-snippet snippet))
3023 (or (not yas/active-field-overlay)
3024 (not (overlay-buffer yas/active-field-overlay))))
3026 ;; stacked expansion: this case is mainly for recent
3027 ;; snippet exits that place us back int the field of
3031 (yas/move-to-field snippet active-field)
3032 (yas/update-mirrors snippet)))
3035 (unless (or (null snippets) snippets-left)
3036 (if snippet-exit-transform
3037 (yas/eval-lisp-no-saves snippet-exit-transform))
3038 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3040 ;; Apropos markers-to-points:
3042 ;; This was found useful for performance reasons, so that an
3043 ;; excessive number of live markers aren't kept around in the
3044 ;; `buffer-undo-list'. However, in `markers-to-points', the
3045 ;; set-to-nil markers can't simply be discarded and replaced with
3046 ;; fresh ones in `points-to-markers'. The original marker that was
3047 ;; just set to nil has to be reused.
3049 ;; This shouldn't bring horrible problems with undo/redo, but it
3052 (defun yas/markers-to-points (snippet)
3053 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3054 where POINT is the original position of the marker and MARKER is
3055 the original marker object with the position set to nil."
3056 (dolist (field (yas/snippet-fields snippet))
3057 (let ((start (marker-position (yas/field-start field)))
3058 (end (marker-position (yas/field-end field))))
3059 (set-marker (yas/field-start field) nil)
3060 (set-marker (yas/field-end field) nil)
3061 (setf (yas/field-start field) (cons start (yas/field-start field)))
3062 (setf (yas/field-end field) (cons end (yas/field-end field))))
3063 (dolist (mirror (yas/field-mirrors field))
3064 (let ((start (marker-position (yas/mirror-start mirror)))
3065 (end (marker-position (yas/mirror-end mirror))))
3066 (set-marker (yas/mirror-start mirror) nil)
3067 (set-marker (yas/mirror-end mirror) nil)
3068 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3069 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3070 (let ((snippet-exit (yas/snippet-exit snippet)))
3072 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3073 (set-marker (yas/exit-marker snippet-exit) nil)
3074 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3076 (defun yas/points-to-markers (snippet)
3077 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3078 is done by setting MARKER to POINT with `set-marker'."
3079 (dolist (field (yas/snippet-fields snippet))
3080 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3081 (car (yas/field-start field))))
3082 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3083 (car (yas/field-end field))))
3084 (dolist (mirror (yas/field-mirrors field))
3085 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3086 (car (yas/mirror-start mirror))))
3087 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3088 (car (yas/mirror-end mirror))))))
3089 (let ((snippet-exit (yas/snippet-exit snippet)))
3091 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3092 (car (yas/exit-marker snippet-exit)))))))
3094 (defun yas/field-contains-point-p (field &optional point)
3095 (let ((point (or point
3097 (and (>= point (yas/field-start field))
3098 (<= point (yas/field-end field)))))
3100 (defun yas/field-text-for-display (field)
3101 "Return the propertized display text for field FIELD. "
3102 (buffer-substring (yas/field-start field) (yas/field-end field)))
3104 (defun yas/undo-in-progress ()
3105 "True if some kind of undo is in progress"
3106 (or undo-in-progress
3107 (eq this-command 'undo)
3108 (eq this-command 'redo)))
3110 (defun yas/make-control-overlay (snippet start end)
3111 "Creates the control overlay that surrounds the snippet and
3113 (let ((overlay (make-overlay start
3118 (overlay-put overlay 'keymap yas/keymap)
3119 (overlay-put overlay 'priority 100)
3120 (overlay-put overlay 'yas/snippet snippet)
3123 (defun yas/skip-and-clear-or-delete-char (&optional field)
3124 "Clears unmodified field if at field start, skips to next tab.
3126 Otherwise deletes a character normally by calling `delete-char'."
3128 (let ((field (or field
3129 (and yas/active-field-overlay
3130 (overlay-buffer yas/active-field-overlay)
3131 (overlay-get yas/active-field-overlay 'yas/field)))))
3133 (not (yas/field-modified-p field))
3134 (eq (point) (marker-position (yas/field-start field))))
3135 (yas/skip-and-clear field)
3138 (call-interactively 'delete-char)))))
3140 (defun yas/skip-and-clear (field)
3141 "Deletes the region of FIELD and sets it modified state to t"
3142 ;; Just before skipping-and-clearing the field, mark its children
3143 ;; fields as modified, too. If the childen have mirrors-in-fields
3144 ;; this prevents them from updating erroneously (we're skipping and
3147 (yas/mark-this-and-children-modified field)
3148 (delete-region (yas/field-start field) (yas/field-end field)))
3150 (defun yas/mark-this-and-children-modified (field)
3151 (setf (yas/field-modified-p field) t)
3152 (let ((fom (yas/field-next field)))
3154 (yas/fom-parent-field fom))
3155 (when (and (eq (yas/fom-parent-field fom) field)
3157 (yas/mark-this-and-children-modified fom))
3158 (setq fom (yas/fom-next fom)))))
3160 (defun yas/make-move-active-field-overlay (snippet field)
3161 "Place the active field overlay in SNIPPET's FIELD.
3163 Move the overlay, or create it if it does not exit."
3164 (if (and yas/active-field-overlay
3165 (overlay-buffer yas/active-field-overlay))
3166 (move-overlay yas/active-field-overlay
3167 (yas/field-start field)
3168 (yas/field-end field))
3169 (setq yas/active-field-overlay
3170 (make-overlay (yas/field-start field)
3171 (yas/field-end field)
3173 (overlay-put yas/active-field-overlay 'priority 100)
3174 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3175 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3176 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3177 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3178 '(yas/on-field-overlay-modification))
3179 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3180 '(yas/on-field-overlay-modification))))
3182 (defvar yas/inhibit-overlay-hooks nil
3183 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3185 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3186 "Clears the field and updates mirrors, conditionally.
3188 Only clears the field if it hasn't been modified and it point it
3189 at field start. This hook doesn't do anything if an undo is in
3191 (unless (or yas/inhibit-overlay-hooks
3192 (yas/undo-in-progress))
3193 (let* ((field (overlay-get overlay 'yas/field))
3194 (number (and field (yas/field-number field)))
3195 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3197 (yas/advance-end-maybe field (overlay-end overlay))
3199 (yas/field-update-display field snippet))
3200 (yas/update-mirrors snippet))
3202 (when (and (not after?)
3203 (not (yas/field-modified-p field))
3204 (eq (point) (if (markerp (yas/field-start field))
3205 (marker-position (yas/field-start field))
3206 (yas/field-start field))))
3207 (yas/skip-and-clear field))
3208 (setf (yas/field-modified-p field) t))))))
3210 ;;; Apropos protection overlays:
3212 ;; These exist for nasty users who will try to delete parts of the
3213 ;; snippet outside the active field. Actual protection happens in
3214 ;; `yas/on-protection-overlay-modification'.
3216 ;; Currently this signals an error which inhibits the command. For
3217 ;; commands that move point (like `kill-line'), point is restored in
3218 ;; the `yas/post-command-handler' using a global
3219 ;; `yas/protection-violation' variable.
3221 ;; Alternatively, I've experimented with an implementation that
3222 ;; commits the snippet before actually calling `this-command'
3223 ;; interactively, and then signals an eror, which is ignored. but
3224 ;; blocks all other million modification hooks. This presented some
3225 ;; problems with stacked expansion.
3228 (defun yas/make-move-field-protection-overlays (snippet field)
3229 "Place protection overlays surrounding SNIPPET's FIELD.
3231 Move the overlays, or create them if they do not exit."
3232 (let ((start (yas/field-start field))
3233 (end (yas/field-end field)))
3234 ;; First check if the (1+ end) is contained in the buffer,
3235 ;; otherwise we'll have to do a bit of cheating and silently
3236 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3237 ;; when using stacked expansion
3239 (when (< (buffer-size) end)
3241 (yas/inhibit-overlay-hooks
3242 (goto-char (point-max))
3244 ;; go on to normal overlay creation/moving
3246 (cond ((and yas/field-protection-overlays
3247 (every #'overlay-buffer yas/field-protection-overlays))
3248 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3249 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3251 (setq yas/field-protection-overlays
3252 (list (make-overlay (1- start) start nil t nil)
3253 (make-overlay end (1+ end) nil t nil)))
3254 (dolist (ov yas/field-protection-overlays)
3255 (overlay-put ov 'face 'yas/field-debug-face)
3256 (overlay-put ov 'yas/snippet snippet)
3257 ;; (overlay-put ov 'evaporate t)
3258 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3260 (defvar yas/protection-violation nil
3261 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3263 Functions in the `post-command-hook', for example
3264 `yas/post-command-handler' can check it and reset its value to
3265 nil. The variables value is the point where the violation
3268 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3269 "Signals a snippet violation, then issues error.
3271 The error should be ignored in `debug-ignored-errors'"
3272 (unless yas/inhibit-overlay-hooks
3273 (cond ((not (or after?
3274 (yas/undo-in-progress)))
3275 (setq yas/protection-violation (point))
3276 (error "Exit the snippet first!")))))
3278 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3281 ;;; Apropos stacked expansion:
3283 ;; the parent snippet does not run its fields modification hooks
3284 ;; (`yas/on-field-overlay-modification' and
3285 ;; `yas/on-protection-overlay-modification') while the child snippet
3286 ;; is active. This means, among other things, that the mirrors of the
3287 ;; parent snippet are not updated, this only happening when one exits
3288 ;; the child snippet.
3290 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3291 ;; bits of code in `yas/expand-snippet' and
3292 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3295 ;; This was thought to be safer in in an undo/redo perpective, but
3296 ;; maybe the correct implementation is to make the globals
3297 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3298 ;; snippet-local and be active even while the child snippet is
3299 ;; running. This would mean a lot of overlay modification hooks
3300 ;; running, but if managed correctly (including overlay priorities)
3301 ;; they should account for all situations...
3304 (defun yas/expand-snippet (content &optional start end expand-env)
3305 "Expand snippet CONTENT at current point.
3307 Text between START and END will be deleted before inserting
3308 template. EXPAND-ENV is are let-style variable to value bindings
3309 considered when expanding the snippet."
3310 (run-hooks 'yas/before-expand-snippet-hook)
3312 ;; If a region is active, set `yas/selected-text'
3313 (setq yas/selected-text
3314 (when (region-active-p)
3315 (prog1 (buffer-substring-no-properties (region-beginning)
3317 (unless start (setq start (region-beginning))
3318 (unless end (setq end (region-end)))))))
3324 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3325 (start (or start (point)))
3326 (end (or end (point)))
3328 (setq yas/indent-original-column (current-column))
3329 ;; Delete the region to delete, this *does* get undo-recorded.
3331 (when (and to-delete
3333 (delete-region start end))
3335 (cond ((listp content)
3336 ;; x) This is a snippet-command
3338 (yas/eval-lisp-no-saves content))
3340 ;; x) This is a snippet-snippet :-)
3342 ;; Narrow the region down to the content, shoosh the
3343 ;; `buffer-undo-list', and create the snippet, the new
3344 ;; snippet updates its mirrors once, so we are left with
3345 ;; some plain text. The undo action for deleting this
3346 ;; plain text will get recorded at the end.
3348 ;; stacked expansion: also shoosh the overlay modification hooks
3350 (narrow-to-region start start)
3351 (let ((buffer-undo-list t))
3352 ;; snippet creation might evaluate users elisp, which
3353 ;; might generate errors, so we have to be ready to catch
3354 ;; them mostly to make the undo information
3356 (setq yas/start-column (save-restriction (widen) (current-column)))
3357 (yas/inhibit-overlay-hooks
3360 (eval `(let* ,expand-env
3362 (yas/snippet-create (point-min) (point-max))))
3364 (yas/snippet-create (point-min) (point-max)))))))
3366 ;; stacked-expansion: This checks for stacked expansion, save the
3367 ;; `yas/previous-active-field' and advance its boudary.
3369 (let ((existing-field (and yas/active-field-overlay
3370 (overlay-buffer yas/active-field-overlay)
3371 (overlay-get yas/active-field-overlay 'yas/field))))
3372 (when existing-field
3373 (setf (yas/snippet-previous-active-field snippet) existing-field)
3374 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3376 ;; Exit the snippet immediately if no fields
3378 (unless (yas/snippet-fields snippet)
3379 (yas/exit-snippet snippet))
3381 ;; Push two undo actions: the deletion of the inserted contents of
3382 ;; the new snippet (without the "key") followed by an apply of
3383 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3385 ;; A small exception, if `yas/also-auto-indent-first-line'
3386 ;; is t and `yas/indent' decides to indent the line to a
3387 ;; point before the actual expansion point, undo would be
3388 ;; messed up. We call the early point "newstart"". case,
3389 ;; and attempt to fix undo.
3391 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3392 (end (overlay-end (yas/snippet-control-overlay snippet))))
3393 (when (< newstart start)
3394 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3395 (push (cons newstart end) buffer-undo-list)
3396 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3398 ;; Now, schedule a move to the first field
3400 (let ((first-field (car (yas/snippet-fields snippet))))
3402 (sit-for 0) ;; fix issue 125
3403 (yas/move-to-field snippet first-field)))
3404 (yas/message 3 "snippet expanded.")
3407 (defun yas/take-care-of-redo (beg end snippet)
3408 "Commits SNIPPET, which in turn pushes an undo action for
3411 Meant to exit in the `buffer-undo-list'."
3412 ;; slightly optimize: this action is only needed for snippets with
3413 ;; at least one field
3414 (when (yas/snippet-fields snippet)
3415 (yas/commit-snippet snippet)))
3417 (defun yas/snippet-revive (beg end snippet)
3418 "Revives the SNIPPET and creates a control overlay from BEG to
3421 BEG and END are, we hope, the original snippets boudaries. All
3422 the markers/points exiting existing inside SNIPPET should point
3423 to their correct locations *at the time the snippet is revived*.
3425 After revival, push the `yas/take-care-of-redo' in the
3427 ;; Reconvert all the points to markers
3429 (yas/points-to-markers snippet)
3430 ;; When at least one editable field existed in the zombie snippet,
3431 ;; try to revive the whole thing...
3433 (let ((target-field (or (yas/snippet-active-field snippet)
3434 (car (yas/snippet-fields snippet)))))
3436 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3437 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3439 (yas/move-to-field snippet target-field)
3441 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3442 buffer-undo-list))))
3444 (defun yas/snippet-create (begin end)
3445 "Creates a snippet from an template inserted between BEGIN and END.
3447 Returns the newly created snippet."
3448 (let ((snippet (yas/make-snippet)))
3450 (yas/snippet-parse-create snippet)
3452 ;; Sort and link each field
3453 (yas/snippet-sort-fields snippet)
3455 ;; Create keymap overlay for snippet
3456 (setf (yas/snippet-control-overlay snippet)
3457 (yas/make-control-overlay snippet (point-min) (point-max)))
3460 (goto-char (point-max))
3465 ;;; Apropos adjacencies and "fom's":
3467 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3468 ;; recently expanded snippet, we might actually have many fields,
3469 ;; mirrors (and the snippet exit) in the very same position in the
3470 ;; buffer. Therefore we need to single-link the
3471 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3472 ;; their original positions in the buffer.
3474 ;; Then we have operation `yas/advance-end-maybe' and
3475 ;; `yas/advance-start-maybe', which conditionally push the starts and
3476 ;; ends of these foms down the chain.
3478 ;; This allows for like the printf with the magic ",":
3480 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3481 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3483 (defun yas/fom-start (fom)
3484 (cond ((yas/field-p fom)
3485 (yas/field-start fom))
3487 (yas/mirror-start fom))
3489 (yas/exit-marker fom))))
3491 (defun yas/fom-end (fom)
3492 (cond ((yas/field-p fom)
3493 (yas/field-end fom))
3495 (yas/mirror-end fom))
3497 (yas/exit-marker fom))))
3499 (defun yas/fom-next (fom)
3500 (cond ((yas/field-p fom)
3501 (yas/field-next fom))
3503 (yas/mirror-next fom))
3505 (yas/exit-next fom))))
3507 (defun yas/fom-parent-field (fom)
3508 (cond ((yas/field-p fom)
3509 (yas/field-parent-field fom))
3511 (yas/mirror-parent-field fom))
3515 (defun yas/calculate-adjacencies (snippet)
3516 "Calculate adjacencies for fields or mirrors of SNIPPET.
3518 This is according to their relative positions in the buffer, and
3519 has to be called before the $-constructs are deleted."
3520 (flet ((yas/fom-set-next-fom (fom nextfom)
3521 (cond ((yas/field-p fom)
3522 (setf (yas/field-next fom) nextfom))
3524 (setf (yas/mirror-next fom) nextfom))
3526 (setf (yas/exit-next fom) nextfom))))
3527 (yas/compare-fom-begs (fom1 fom2)
3528 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3530 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3531 (yas/link-foms (fom1 fom2)
3532 (yas/fom-set-next-fom fom1 fom2)))
3533 ;; make some yas/field, yas/mirror and yas/exit soup
3535 (when (yas/snippet-exit snippet)
3536 (push (yas/snippet-exit snippet) soup))
3537 (dolist (field (yas/snippet-fields snippet))
3539 (dolist (mirror (yas/field-mirrors field))
3540 (push mirror soup)))
3543 #'yas/compare-fom-begs))
3545 (reduce #'yas/link-foms soup)))))
3547 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3548 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3550 Use the tighest containing field if more than one field contains
3551 the mirror. Intended to be called *before* the dollar-regions are
3553 (let ((min (point-min))
3555 (dolist (field (yas/snippet-fields snippet))
3556 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3557 (<= (yas/mirror-end mirror) (yas/field-end field))
3558 (< min (yas/field-start field))
3559 (< (yas/field-end field) max))
3560 (setq min (yas/field-start field)
3561 max (yas/field-end field))
3562 (setf (yas/mirror-parent-field mirror) field)))))
3564 (defun yas/advance-end-maybe (fom newend)
3565 "Maybe advance FOM's end to NEWEND if it needs it.
3569 * call `yas/advance-start-maybe' on FOM's next fom.
3571 * in case FOM is field call `yas/advance-end-maybe' on its parent
3574 Also, if FOM is an exit-marker, always call
3575 `yas/advance-start-maybe' on its next fom. This is beacuse
3576 exit-marker have identical start and end markers.
3579 (cond ((and fom (< (yas/fom-end fom) newend))
3580 (set-marker (yas/fom-end fom) newend)
3581 (yas/advance-start-maybe (yas/fom-next fom) newend)
3582 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3584 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3586 (defun yas/advance-start-maybe (fom newstart)
3587 "Maybe advance FOM's start to NEWSTART if it needs it.
3589 If it does, also call `yas/advance-end-maybe' on FOM."
3590 (when (and fom (< (yas/fom-start fom) newstart))
3591 (set-marker (yas/fom-start fom) newstart)
3592 (yas/advance-end-maybe fom newstart)))
3594 (defun yas/advance-end-of-parents-maybe (field newend)
3595 "Like `yas/advance-end-maybe' but for parent fields.
3597 Only works for fields and doesn't care about the start of the
3598 next FOM. Works its way up recursively for parents of parents."
3600 (< (yas/field-end field) newend))
3601 (set-marker (yas/field-end field) newend)
3602 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3604 (defvar yas/dollar-regions nil
3605 "When expanding the snippet the \"parse-create\" functions add
3606 cons cells to this var")
3608 (defun yas/snippet-parse-create (snippet)
3609 "Parse a recently inserted snippet template, creating all
3610 necessary fields, mirrors and exit points.
3612 Meant to be called in a narrowed buffer, does various passes"
3613 (let ((parse-start (point)))
3614 ;; Reset the yas/dollar-regions
3616 (setq yas/dollar-regions nil)
3617 ;; protect escaped quote, backquotes and backslashes
3619 (yas/protect-escapes nil `(?\\ ?` ?'))
3620 ;; replace all backquoted expressions
3622 (goto-char parse-start)
3623 (yas/replace-backquotes)
3624 ;; protect escapes again since previous steps might have generated
3625 ;; more characters needing escaping
3627 (goto-char parse-start)
3628 (yas/protect-escapes)
3629 ;; parse fields with {}
3631 (goto-char parse-start)
3632 (yas/field-parse-create snippet)
3633 ;; parse simple mirrors and fields
3635 (goto-char parse-start)
3636 (yas/simple-mirror-parse-create snippet)
3637 ;; parse mirror transforms
3639 (goto-char parse-start)
3640 (yas/transform-mirror-parse-create snippet)
3641 ;; calculate adjacencies of fields and mirrors
3643 (yas/calculate-adjacencies snippet)
3644 ;; Delete $-constructs
3646 (yas/delete-regions yas/dollar-regions)
3649 (goto-char parse-start)
3650 (yas/restore-escapes)
3651 ;; update mirrors for the first time
3653 (yas/update-mirrors snippet)
3654 ;; indent the best we can
3656 (goto-char parse-start)
3657 (yas/indent snippet)))
3659 (defun yas/indent-according-to-mode (snippet-markers)
3660 "Indent current line according to mode, preserving
3662 ;;; Apropos indenting problems....
3664 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3665 ;; is available. Some implementations of these functions delete text
3666 ;; before they insert. If there happens to be a marker just after
3667 ;; the text being deleted, the insertion actually happens after the
3668 ;; marker, which misplaces it.
3670 ;; This would also happen if we had used overlays with the
3671 ;; `front-advance' property set to nil.
3673 ;; This is why I have these `trouble-markers', they are the ones at
3674 ;; they are the ones at the first non-whitespace char at the line
3675 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3676 ;; we should be at the correct to restore them to. All other
3677 ;; non-trouble-markers have been *pushed* and don't need special
3680 (goto-char (yas/real-line-beginning))
3681 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3687 (indent-according-to-mode)
3688 (error (yas/message 3 "Warning: `yas/indent-according-to-mode' having problems running %s" indent-line-function)
3690 (mapc #'(lambda (marker)
3691 (set-marker marker (point)))
3694 (defvar yas/indent-original-column nil)
3695 (defun yas/indent (snippet)
3696 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3697 ;; Look for those $>
3699 (while (re-search-forward "$>" nil t)
3700 (delete-region (match-beginning 0) (match-end 0))
3701 (when (not (eq yas/indent-line 'auto))
3702 (yas/indent-according-to-mode snippet-markers))))
3703 ;; Now do stuff for 'fixed and 'auto
3705 (cond ((eq yas/indent-line 'fixed)
3706 (while (and (zerop (forward-line))
3707 (zerop (current-column)))
3708 (indent-to-column yas/indent-original-column)))
3709 ((eq yas/indent-line 'auto)
3710 (let ((end (set-marker (make-marker) (point-max)))
3711 (indent-first-line-p yas/also-auto-indent-first-line))
3712 (while (and (zerop (if indent-first-line-p
3715 (setq indent-first-line-p nil))
3719 (yas/indent-according-to-mode snippet-markers))))
3723 (defun yas/collect-snippet-markers (snippet)
3724 "Make a list of all the markers used by SNIPPET."
3726 (dolist (field (yas/snippet-fields snippet))
3727 (push (yas/field-start field) markers)
3728 (push (yas/field-end field) markers)
3729 (dolist (mirror (yas/field-mirrors field))
3730 (push (yas/mirror-start mirror) markers)
3731 (push (yas/mirror-end mirror) markers)))
3732 (let ((snippet-exit (yas/snippet-exit snippet)))
3733 (when (and snippet-exit
3734 (marker-buffer (yas/exit-marker snippet-exit)))
3735 (push (yas/exit-marker snippet-exit) markers)))
3738 (defun yas/real-line-beginning ()
3739 (let ((c (char-after (line-beginning-position)))
3740 (n (line-beginning-position)))
3741 (while (or (eql c ?\ )
3744 (setq c (char-after n)))
3747 (defun yas/escape-string (escaped)
3748 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3750 (defun yas/protect-escapes (&optional text escaped)
3751 "Protect all escaped characters with their numeric ASCII value.
3753 With optional string TEXT do it in string instead of buffer."
3754 (let ((changed-text text)
3755 (text-provided-p text))
3756 (mapc #'(lambda (escaped)
3758 (yas/replace-all (concat "\\" (char-to-string escaped))
3759 (yas/escape-string escaped)
3760 (when text-provided-p changed-text))))
3761 (or escaped yas/escaped-characters))
3764 (defun yas/restore-escapes (&optional text escaped)
3765 "Restore all escaped characters from their numeric ASCII value.
3767 With optional string TEXT do it in string instead of the buffer."
3768 (let ((changed-text text)
3769 (text-provided-p text))
3770 (mapc #'(lambda (escaped)
3772 (yas/replace-all (yas/escape-string escaped)
3773 (char-to-string escaped)
3774 (when text-provided-p changed-text))))
3775 (or escaped yas/escaped-characters))
3778 (defun yas/replace-backquotes ()
3779 "Replace all the \"`(lisp-expression)`\"-style expression
3780 with their evaluated value"
3781 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3782 (let ((current-string (match-string 1)) transformed)
3783 (delete-region (match-beginning 0) (match-end 0))
3784 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3785 (goto-char (match-beginning 0))
3786 (when transformed (insert transformed)))))
3788 (defun yas/scan-sexps (from count)
3790 (with-syntax-table (standard-syntax-table)
3791 (scan-sexps from count))
3795 (defun yas/make-marker (pos)
3796 "Create a marker at POS with `nil' `marker-insertion-type'"
3797 (let ((marker (set-marker (make-marker) pos)))
3798 (set-marker-insertion-type marker nil)
3801 (defun yas/field-parse-create (snippet &optional parent-field)
3802 "Parse most field expressions, except for the simple one \"$n\".
3804 The following count as a field:
3806 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3808 * \"${n: text$(expression)}, the same with a lisp expression;
3809 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3811 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3813 When multiple expressions are found, only the last one counts."
3816 (while (re-search-forward yas/field-regexp nil t)
3817 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3818 (number (and (match-string-no-properties 1)
3819 (string-to-number (match-string-no-properties 1))))
3820 (brand-new-field (and real-match-end-0
3821 ;; break if on "$(" immediately
3822 ;; after the ":", this will be
3823 ;; caught as a mirror with
3825 (not (save-match-data
3826 (eq (string-match "$[ \t\n]*("
3827 (match-string-no-properties 2)) 0)))
3828 ;; allow ${0: some exit text}
3829 ;; (not (and number (zerop number)))
3830 (yas/make-field number
3831 (yas/make-marker (match-beginning 2))
3832 (yas/make-marker (1- real-match-end-0))
3834 (when brand-new-field
3835 (goto-char real-match-end-0)
3836 (push (cons (1- real-match-end-0) real-match-end-0)
3838 (push (cons (match-beginning 0) (match-beginning 2))
3840 (push brand-new-field (yas/snippet-fields snippet))
3843 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3844 (goto-char (point-min))
3845 (yas/field-parse-create snippet brand-new-field)))))))
3846 ;; if we entered from a parent field, now search for the
3847 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3848 ;; primary field transformations
3852 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3853 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3854 ;; commit the primary field transformation if:
3856 ;; 1. we don't find it in yas/dollar-regions (a subnested
3857 ;; field) might have already caught it.
3859 ;; 2. we really make sure we have either two '$' or some
3860 ;; text and a '$' after the colon ':'. This is a FIXME: work
3861 ;; my regular expressions and end these ugly hacks.
3863 (when (and real-match-end-1
3864 (not (member (cons (match-beginning 0)
3866 yas/dollar-regions))
3868 (char-before (1- (match-beginning 1))))))
3869 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3871 (setf (yas/field-transform parent-field)
3872 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3873 (push (cons (match-beginning 0) real-match-end-1)
3874 yas/dollar-regions)))))))
3876 (defun yas/transform-mirror-parse-create (snippet)
3877 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3878 (while (re-search-forward yas/transform-mirror-regexp nil t)
3879 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3880 (number (string-to-number (match-string-no-properties 1)))
3882 (not (zerop number))
3883 (yas/snippet-find-field snippet number)))
3885 (and real-match-end-0
3887 (yas/make-mirror (yas/make-marker (match-beginning 0))
3888 (yas/make-marker (match-beginning 0))
3890 (yas/restore-escapes
3891 (buffer-substring-no-properties (match-beginning 2)
3892 (1- real-match-end-0))))))))
3893 (when brand-new-mirror
3894 (push brand-new-mirror
3895 (yas/field-mirrors field))
3896 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3897 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3899 (defun yas/simple-mirror-parse-create (snippet)
3900 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3901 (while (re-search-forward yas/simple-mirror-regexp nil t)
3902 (let ((number (string-to-number (match-string-no-properties 1))))
3903 (cond ((zerop number)
3905 (setf (yas/snippet-exit snippet)
3906 (yas/make-exit (yas/make-marker (match-end 0))))
3908 (goto-char (match-beginning 0))
3909 (when yas/wrap-around-region
3910 (cond (yas/selected-text
3911 (insert yas/selected-text))
3912 ((and (eq yas/wrap-around-region 'cua)
3915 (insert (prog1 (get-register ?0)
3916 (set-register ?0 nil))))))
3917 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3918 yas/dollar-regions)))
3920 (let ((field (yas/snippet-find-field snippet number)))
3922 (let ((brand-new-mirror (yas/make-mirror
3923 (yas/make-marker (match-beginning 0))
3924 (yas/make-marker (match-beginning 0))
3926 (push brand-new-mirror
3927 (yas/field-mirrors field))
3928 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
3929 (push (yas/make-field number
3930 (yas/make-marker (match-beginning 0))
3931 (yas/make-marker (match-beginning 0))
3933 (yas/snippet-fields snippet))))
3934 (push (cons (match-beginning 0) (match-end 0))
3935 yas/dollar-regions))))))
3937 (defun yas/delete-regions (regions)
3938 "Sort disjuct REGIONS by start point, then delete from the back."
3939 (mapc #'(lambda (reg)
3940 (delete-region (car reg) (cdr reg)))
3943 (>= (car r1) (car r2))))))
3945 (defun yas/update-mirrors (snippet)
3946 "Updates all the mirrors of SNIPPET."
3948 (let* ((fields (copy-list (yas/snippet-fields snippet)))
3949 (field (car fields)))
3951 (dolist (mirror (yas/field-mirrors field))
3952 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
3953 ;; updatte this mirror
3955 (yas/mirror-update-display mirror field)
3956 ;; for mirrors-in-fields: schedule a possible
3957 ;; parent field for reupdting later on
3959 (when mirror-parent-field
3960 (add-to-list 'fields mirror-parent-field 'append #'eq))
3961 ;; `yas/place-overlays' is needed if the active field and
3962 ;; protected overlays have been changed because of insertions
3963 ;; in `yas/mirror-update-display'
3965 (when (eq field (yas/snippet-active-field snippet))
3966 (yas/place-overlays snippet field))))
3967 (setq fields (cdr fields))
3968 (setq field (car fields))))))
3970 (defun yas/mirror-update-display (mirror field)
3971 "Update MIRROR according to FIELD (and mirror transform)."
3973 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
3974 (reflection (and (not (and mirror-parent-field
3975 (yas/field-modified-p mirror-parent-field)))
3976 (or (yas/apply-transform mirror field 'empty-on-nil)
3977 (yas/field-text-for-display field)))))
3978 (when (and reflection
3979 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
3980 (yas/mirror-end mirror)))))
3981 (goto-char (yas/mirror-start mirror))
3982 (yas/inhibit-overlay-hooks
3983 (insert reflection))
3984 (if (> (yas/mirror-end mirror) (point))
3985 (delete-region (point) (yas/mirror-end mirror))
3986 (set-marker (yas/mirror-end mirror) (point))
3987 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
3988 ;; super-special advance
3989 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
3991 (defun yas/field-update-display (field snippet)
3992 "Much like `yas/mirror-update-display', but for fields"
3993 (when (yas/field-transform field)
3994 (let ((transformed (and (not (eq (yas/field-number field) 0))
3995 (yas/apply-transform field field)))
3997 (when (and transformed
3998 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
3999 (yas/field-end field)))))
4000 (setf (yas/field-modified-p field) t)
4001 (goto-char (yas/field-start field))
4002 (yas/inhibit-overlay-hooks
4003 (insert transformed)
4004 (if (> (yas/field-end field) (point))
4005 (delete-region (point) (yas/field-end field))
4006 (set-marker (yas/field-end field) (point))
4007 (yas/advance-start-maybe (yas/field-next field) (point)))
4011 ;;; Post-command hooks:
4013 (defvar yas/post-command-runonce-actions nil
4014 "List of actions to run once in `post-command-hook'.
4016 Each element of this list looks like (FN . ARGS) where FN is
4017 called with ARGS as its arguments after the currently executing
4020 After all actions have been run, this list is emptied, and after
4021 that the rest of `yas/post-command-handler' runs.")
4023 (defun yas/post-command-handler ()
4024 "Handles various yasnippet conditions after each command."
4025 (when yas/post-command-runonce-actions
4027 (mapc #'(lambda (fn-and-args)
4028 (apply (car fn-and-args)
4030 yas/post-command-runonce-actions)
4031 (error (yas/message 3 "Problem running `yas/post-command-runonce-actions'!")))
4032 (setq yas/post-command-runonce-actions nil))
4033 (cond (yas/protection-violation
4034 (goto-char yas/protection-violation)
4035 (setq yas/protection-violation nil))
4036 ((eq 'undo this-command)
4038 ;; After undo revival the correct field is sometimes not
4039 ;; restored correctly, this condition handles that
4041 (let* ((snippet (car (yas/snippets-at-point)))
4042 (target-field (and snippet
4043 (find-if-not #'(lambda (field)
4044 (yas/field-probably-deleted-p snippet field))
4046 (cons (yas/snippet-active-field snippet)
4047 (yas/snippet-fields snippet)))))))
4049 (yas/move-to-field snippet target-field))))
4050 ((not (yas/undo-in-progress))
4051 ;; When not in an undo, check if we must commit the snippet
4052 ;; (user exited it).
4053 (yas/check-commit-snippet))))
4057 (put 'yas/expand 'function-documentation
4058 '(yas/expand-from-trigger-key-doc))
4059 (defun yas/expand-from-trigger-key-doc ()
4060 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4061 (let ((fallback-description
4062 (cond ((eq yas/fallback-behavior 'call-other-command)
4063 (let* ((yas/minor-mode nil)
4064 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4066 (format " call command `%s'." (pp-to-string fallback)))
4068 ((eq yas/fallback-behavior 'return-nil)
4071 ", defer to `yas/fallback-behaviour' :-)"))))
4072 (concat "Expand a snippet before point. If no snippet
4073 expansion is possible,"
4074 fallback-description
4075 "\n\nOptional argument FIELD is for non-interactive use and is an
4076 object satisfying `yas/field-p' to restrict the expansion to.")))
4078 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4079 (defun yas/expand-from-keymap-doc ()
4080 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4081 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4082 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4083 (when (eq this-command 'describe-key)
4084 (let* ((vec (this-single-command-keys))
4085 (templates (mapcan #'(lambda (table)
4086 (yas/fetch table vec))
4087 (yas/get-snippet-tables)))
4088 (yas/direct-keymaps nil)
4089 (fallback (key-binding vec)))
4090 (concat "In this case, "
4092 (concat "these snippets are bound to this key:\n"
4093 (yas/template-pretty-list templates)
4094 "\n\nIf none of these expands, "))
4096 (format "fallback `%s' will be called." (pp-to-string fallback)))
4097 "no fallback keybinding is called."))))))
4099 (defun yas/template-pretty-list (templates)
4101 (yas/buffer-local-condition 'always))
4102 (dolist (plate templates)
4103 (setq acc (concat acc "\n*) "
4104 (propertize (concat "\\\\snippet `" (car plate) "'")
4105 'yasnippet (cdr plate)))))
4108 (define-button-type 'help-snippet-def
4109 :supertype 'help-xref
4110 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4111 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4113 (defun yas/snippet-description-finish-runonce ()
4114 "Final adjustments for the help buffer when snippets are concerned."
4115 (yas/create-snippet-xrefs)
4116 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4118 (defun yas/create-snippet-xrefs ()
4120 (goto-char (point-min))
4121 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4122 (let ((template (get-text-property (match-beginning 1)
4125 (help-xref-button 1 'help-snippet-def template)
4126 (kill-region (match-end 1) (match-end 0))
4127 (kill-region (match-beginning 0) (match-beginning 1)))))))
4129 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4130 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4132 Remaining args as in `yas/expand-snippet'."
4133 (let* ((table (gethash mode-symbol yas/tables))
4134 (yas/current-template (and table
4135 (gethash uuid (yas/table-uuidhash table)))))
4136 (when yas/current-template
4137 (yas/expand-snippet (yas/template-content yas/current-template)))))
4142 (defvar yas/verbosity 4
4143 "Log level for `yas/message' 4 means trace most anything, 0 means nothing.")
4144 (defun yas/message (level message &rest args)
4145 (when (> yas/verbosity level)
4146 (message (apply #'yas/format message args))))
4148 (defun yas/format (format-control &rest format-args)
4149 (apply #'format (concat "[yas] " format-control) format-args))
4154 ;; `locate-dominating-file'
4155 ;; `region-active-p'
4157 ;; added for compatibility in emacs < 23
4158 (unless (>= emacs-major-version 23)
4159 (unless (fboundp 'region-active-p)
4160 (defun region-active-p () (and transient-mark-mode mark-active)))
4162 (unless (fboundp 'locate-dominating-file)
4163 (defvar locate-dominating-stop-dir-regexp
4164 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4165 "Regexp of directory names which stop the search in `locate-dominating-file'.
4166 Any directory whose name matches this regexp will be treated like
4167 a kind of root directory by `locate-dominating-file' which will stop its search
4168 when it bumps into it.
4169 The default regexp prevents fruitless and time-consuming attempts to find
4170 special files in directories in which filenames are interpreted as hostnames,
4171 or mount points potentially requiring authentication as a different user.")
4173 (defun locate-dominating-file (file name)
4174 "Look up the directory hierarchy from FILE for a file named NAME.
4175 Stop at the first parent directory containing a file NAME,
4176 and return the directory. Return nil if not found."
4177 ;; We used to use the above locate-dominating-files code, but the
4178 ;; directory-files call is very costly, so we're much better off doing
4179 ;; multiple calls using the code in here.
4181 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4182 ;; `name' in /home or in /.
4183 (setq file (abbreviate-file-name file))
4186 ;; `user' is not initialized outside the loop because
4187 ;; `file' may not exist, so we may have to walk up part of the
4188 ;; hierarchy before we find the "initial UUID".
4191 (while (not (or root
4193 ;; FIXME: Disabled this heuristic because it is sometimes
4195 ;; As a heuristic, we stop looking up the hierarchy of
4196 ;; directories as soon as we find a directory belonging
4197 ;; to another user. This should save us from looking in
4198 ;; things like /net and /afs. This assumes that all the
4199 ;; files inside a project belong to the same user.
4200 ;; (let ((prev-user user))
4201 ;; (setq user (nth 2 (file-attributes file)))
4202 ;; (and prev-user (not (equal user prev-user))))
4203 (string-match locate-dominating-stop-dir-regexp file)))
4204 (setq try (file-exists-p (expand-file-name name file)))
4205 (cond (try (setq root file))
4206 ((equal file (setq prev-file file
4207 file (file-name-directory
4208 (directory-file-name file))))
4212 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4213 ;; (when it execute forward-char) and interrupt the after change
4214 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4215 ;; invoked. Here's a way to reproduce it:
4217 ;; # open a *new* Emacs.
4218 ;; # load yasnippet.
4219 ;; # open a *new* .cpp file.
4220 ;; # input "inc" and press TAB to expand the snippet.
4221 ;; # select the `#include <...>` snippet.
4222 ;; # type inside `<>`
4224 (defadvice c-neutralize-syntax-in-CPP
4225 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4226 "Adviced `c-neutralize-syntax-in-CPP' to properly
4227 handle the end-of-buffer error fired in it by calling
4228 `forward-char' at the end of buffer."
4231 (error (message (error-message-string err)))))
4233 ;; disable c-electric-* serial command in YAS fields
4234 (add-hook 'c-mode-common-hook
4236 (dolist (k '(":" ">" ";" "<" "{" "}"))
4237 (define-key (symbol-value (make-local-variable 'yas/keymap))
4238 k 'self-insert-command))))
4240 (provide 'yasnippet)
4242 ;;; yasnippet.el ends here