1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://github.com/capitaomorte/yasnippet
10 ;; Keywords: convenience, emulation
11 ;; URL: http://github.com/capitaomorte/yasnippet
12 ;; EmacsWiki: YaSnippetMode
14 ;; This file is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; This file is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
31 ;; Basic steps to setup:
33 ;; (add-to-list 'load-path
34 ;; "~/.emacs.d/plugins/yasnippet")
35 ;; (require 'yasnippet)
36 ;; (yas/global-mode 1)
39 ;; Interesting variables are:
43 ;; The directory where user-created snippets are to be
44 ;; stored. Can also be a list of directories. In that case,
45 ;; when used for bulk (re)loading of snippets (at startup or
46 ;; via `yas/reload-all'), directories appearing earlier in
47 ;; the list shadow other dir's snippets. Also, the first
48 ;; directory is taken as the default for storing the user's
51 ;; The deprecated `yas/root-directory' aliases this variable
52 ;; for backward-compatibility.
56 ;; A local variable that you can set in a hook to override
57 ;; snippet-lookup based on major mode. It is a a symbol (or
58 ;; list of symbols) that correspond to subdirectories of
59 ;; `yas/snippet-dirs' and is used for deciding which
60 ;; snippets to consider for the active buffer.
62 ;; Deprecated `yas/mode-symbol' aliases this variable for
63 ;; backward-compatibility.
65 ;; Major commands are:
69 ;; Try to expand snippets before point. In `yas/minor-mode',
70 ;; this is bound to `yas/trigger-key' which you can customize.
72 ;; M-x yas/load-directory
74 ;; Prompts you for a directory hierarchy of snippets to load.
76 ;; M-x yas/insert-snippet
78 ;; Prompts you for possible snippet expansion if that is
79 ;; possible according to buffer-local and snippet-local
80 ;; expansion conditions. With prefix argument, ignore these
83 ;; M-x yas/find-snippets
85 ;; Lets you find the snippet files in the correct
86 ;; subdirectory of `yas/snippet-dirs', according to the
87 ;; active major mode (if it exists) like
88 ;; `find-file-other-window'.
90 ;; M-x yas/visit-snippet-file
92 ;; Prompts you for possible snippet expansions like
93 ;; `yas/insert-snippet', but instead of expanding it, takes
94 ;; you directly to the snippet definition's file, if it
97 ;; M-x yas/new-snippet
99 ;; Lets you create a new snippet file in the correct
100 ;; subdirectory of `yas/snippet-dirs', according to the
101 ;; active major mode.
103 ;; M-x yas/load-snippet-buffer
105 ;; When editing a snippet, this loads the snippet. This is
106 ;; bound to "C-c C-c" while in the `snippet-mode' editing
109 ;; M-x yas/tryout-snippet
111 ;; When editing a snippet, this opens a new empty buffer,
112 ;; sets it to the appropriate major mode and inserts the
113 ;; snippet there, so you can see what it looks like. This is
114 ;; bound to "C-c C-t" while in `snippet-mode'.
116 ;; M-x yas/describe-tables
118 ;; Lists known snippets in a separate buffer. User is
119 ;; prompted as to whether only the currently active tables
120 ;; are to be displayed, or all the tables for all major
123 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
124 ;; can optionally use it the preferred "prompting method", puting in
125 ;; your .emacs file, for example:
127 ;; (require 'dropdown-list)
128 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
130 ;; yas/completing-prompt))
132 ;; Also check out the customization group
134 ;; M-x customize-group RET yasnippet RET
136 ;; If you use the customization group to set variables
137 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
138 ;; "yasnippet.el" is present in the `load-path' *before* the
139 ;; `custom-set-variables' is executed in your .emacs file.
141 ;; For more information and detailed usage, refer to the project page:
142 ;; http://github.com/capitaomorte/yasnippet
152 ;;; User customizable variables
154 (defgroup yasnippet nil
155 "Yet Another Snippet extension"
158 (defvar yas/load-file-name load-file-name
159 "Store the filename that yasnippet.el was originally loaded from.")
160 (defcustom yas/snippet-dirs (remove nil
161 (list "~/.emacs.d/snippets"
162 (when yas/load-file-name
163 (concat (file-name-directory yas/load-file-name) "snippets"))))
164 "Directory or list of snippet dirs for each major mode.
166 The directory where user-created snippets are to be stored. Can
167 also be a list of directories. In that case, when used for
168 bulk (re)loading of snippets (at startup or via
169 `yas/reload-all'), directories appearing earlier in the list
170 shadow other dir's snippets. Also, the first directory is taken
171 as the default for storing the user's new snippets."
172 :type '(choice (string :tag "Single directory (string)")
173 (repeat :args (string) :tag "List of directories (strings)"))
176 :set #'(lambda (symbol new)
177 (let ((old (and (boundp symbol)
178 (symbol-value symbol))))
179 (set-default symbol new)
180 (unless (or (not (fboundp 'yas/reload-all))
183 (defun yas/snippet-dirs ()
184 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
185 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
187 (defcustom yas/prompt-functions '(yas/x-prompt
189 yas/completing-prompt
192 "Functions to prompt for keys, templates, etc interactively.
194 These functions are called with the following arguments:
196 - PROMPT: A string to prompt the user
198 - CHOICES: a list of strings or objects.
200 - optional DISPLAY-FN : A function that, when applied to each of
201 the objects in CHOICES will return a string.
203 The return value of any function you put here should be one of
204 the objects in CHOICES, properly formatted with DISPLAY-FN (if
207 - To signal that your particular style of prompting is
208 unavailable at the moment, you can also have the function return
211 - To signal that the user quit the prompting process, you can
214 (signal 'quit \"user quit!\")."
215 :type '(repeat function)
218 (defcustom yas/indent-line 'auto
219 "Controls indenting applied to a recent snippet expansion.
221 The following values are possible:
223 - `fixed' Indent the snippet to the current column;
225 - `auto' Indent each line of the snippet with `indent-according-to-mode'
227 Every other value means don't apply any snippet-side indendation
228 after expansion (the manual per-line \"$>\" indentation still
230 :type '(choice (const :tag "Nothing" nothing)
231 (const :tag "Fixed" fixed)
232 (const :tag "Auto" auto))
235 (defcustom yas/also-auto-indent-first-line nil
236 "Non-nil means also auto indent first line according to mode.
238 Naturally this is only valid when `yas/indent-line' is `auto'"
242 (defcustom yas/snippet-revival t
243 "Non-nil means re-activate snippet fields after undo/redo."
247 (defcustom yas/trigger-key "TAB"
248 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
250 Value is a string that is converted to the internal Emacs key
251 representation using `read-kbd-macro'."
254 :set #'(lambda (symbol key)
255 (let ((old (and (boundp symbol)
256 (symbol-value symbol))))
257 (set-default symbol key)
258 ;; On very first loading of this defcustom,
259 ;; `yas/trigger-key' is *not* loaded.
260 (if (fboundp 'yas/trigger-key-reload)
261 (yas/trigger-key-reload old)))))
263 (defcustom yas/next-field-key '("TAB" "<tab>")
264 "The key to navigate to next field when a snippet is active.
266 Value is a string that is converted to the internal Emacs key
267 representation using `read-kbd-macro'.
269 Can also be a list of strings."
270 :type '(choice (string :tag "String")
271 (repeat :args (string) :tag "List of strings"))
273 :set #'(lambda (symbol val)
274 (set-default symbol val)
275 (if (fboundp 'yas/init-yas-in-snippet-keymap)
276 (yas/init-yas-in-snippet-keymap))))
279 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
280 "The key to navigate to previous field when a snippet is active.
282 Value is a string that is converted to the internal Emacs key
283 representation using `read-kbd-macro'.
285 Can also be a list of strings."
286 :type '(choice (string :tag "String")
287 (repeat :args (string) :tag "List of strings"))
289 :set #'(lambda (symbol val)
290 (set-default symbol val)
291 (if (fboundp 'yas/init-yas-in-snippet-keymap)
292 (yas/init-yas-in-snippet-keymap))))
294 (defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
295 "The key to clear the currently active field.
297 Value is a string that is converted to the internal Emacs key
298 representation using `read-kbd-macro'.
300 Can also be a list of strings."
301 :type '(choice (string :tag "String")
302 (repeat :args (string) :tag "List of strings"))
304 :set #'(lambda (symbol val)
305 (set-default symbol val)
306 (if (fboundp 'yas/init-yas-in-snippet-keymap)
307 (yas/init-yas-in-snippet-keymap))))
309 (defcustom yas/triggers-in-field nil
310 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
312 Otherwise, `yas/next-field-key' just tries to move on to the next
317 (defcustom yas/fallback-behavior 'call-other-command
318 "How to act when `yas/trigger-key' does *not* expand a snippet.
320 - `call-other-command' means try to temporarily disable YASnippet
321 and call the next command bound to `yas/trigger-key'.
323 - nil or the symbol `return-nil' mean do nothing. (and
324 `yas/expand-returns' nil)
326 - A lisp form (apply COMMAND . ARGS) means interactively call
327 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
328 with ARGS as arguments."
329 :type '(choice (const :tag "Call previous command" call-other-command)
330 (const :tag "Do nothing" return-nil))
333 (defcustom yas/choose-keys-first nil
334 "If non-nil, prompt for snippet key first, then for template.
336 Otherwise prompts for all possible snippet names.
338 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
342 (defcustom yas/choose-tables-first nil
343 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
345 Otherwise, user chooses between the merging together of all
348 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
352 (defcustom yas/use-menu 'abbreviate
353 "Display a YASnippet menu in the menu bar.
355 When non-nil, submenus for each snippet table will be listed
356 under the menu \"Yasnippet\".
358 - If set to `real-modes' only submenus whose name more or less
359 corresponds to a major mode are listed.
361 - If set to `abbreviate', only the current major-mode
362 menu and the modes set in `yas/extra-modes' are listed.
364 Any other non-nil value, every submenu is listed."
365 :type '(choice (const :tag "Full" t)
366 (const :tag "Real modes only" real-modes)
367 (const :tag "Abbreviate" abbreviate))
370 (defcustom yas/trigger-symbol " =>"
371 "The text that will be used in menu to represent the trigger."
375 (defcustom yas/wrap-around-region nil
376 "If non-nil, snippet expansion wraps around selected region.
378 The wrapping occurs just before the snippet's exit marker. This
379 can be overriden on a per-snippet basis."
383 (defcustom yas/good-grace t
384 "If non-nil, don't raise errors in inline elisp evaluation.
386 An error string \"[yas] error\" is returned instead."
390 (defcustom yas/visit-from-menu nil
391 "If non-nil visit snippets's files from menu, instead of expanding them.
393 This cafn only work when snippets are loaded from files."
397 (defcustom yas/expand-only-for-last-commands nil
398 "List of `last-command' values to restrict tab-triggering to, or nil.
400 Leave this set at nil (the default) to be able to trigger an
401 expansion simply by placing the cursor after a valid tab trigger,
402 using whichever commands.
404 Optionallly, set this to something like '(self-insert-command) if
405 you to wish restrict expansion to only happen when the last
406 letter of the snippet tab trigger was typed immediately before
407 the trigger key itself."
408 :type '(repeat function)
411 ;; Only two faces, and one of them shouldn't even be used...
413 (defface yas/field-highlight-face
414 '((t (:inherit 'region)))
415 "The face used to highlight the currently active field of a snippet"
418 (defface yas/field-debug-face
420 "The face used for debugging some overlays normally hidden"
424 ;;; User can also customize the next defvars
425 (defun yas/define-some-keys (keys keymap definition)
426 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
427 (let ((keys (or (and (listp keys) keys)
430 (define-key keymap (read-kbd-macro key) definition))))
433 (let ((map (make-sparse-keymap)))
434 (mapc #'(lambda (binding)
435 (yas/define-some-keys (car binding) map (cdr binding)))
436 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
437 (,yas/prev-field-key . yas/prev-field)
438 ("C-g" . yas/abort-snippet)
439 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
441 "The keymap active while a snippet expansion is in progress.")
443 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
444 "List of character syntaxes used to find a trigger key before point.
445 The list is tried in the order while scanning characters
446 backwards from point. For example, if the list is '(\"w\" \"w_\")
447 first look for trigger keys which are composed exclusively of
448 \"word\"-syntax characters, and then, if that fails, look for
449 keys which are either of \"word\" or \"symbol\"
450 syntax. Triggering after
454 will, according to the \"w\" element first try \"bar\". If that
455 isn't a trigger key, \"foo-bar\" is tried, respecting a second
458 (defvar yas/after-exit-snippet-hook
460 "Hooks to run after a snippet exited.
462 The hooks will be run in an environment where some variables bound to
465 `yas/snippet-beg' : The beginning of the region of the snippet.
467 `yas/snippet-end' : Similar to beg.
469 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
471 (defvar yas/before-expand-snippet-hook
473 "Hooks to run just before expanding a snippet.")
475 (defvar yas/buffer-local-condition
476 '(if (and (or (fourth (syntax-ppss))
477 (fifth (syntax-ppss)))
478 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
479 '(require-snippet-condition . force-in-comment)
481 "Snippet expanding condition.
483 This variable is a lisp form which is evaluated everytime a
484 snippet expansion is attemped:
486 * If it evaluates to nil, no snippets can be expanded.
488 * If it evaluates to the a cons (require-snippet-condition
491 * Snippets bearing no \"# condition:\" directive are not
494 * Snippets bearing conditions that evaluate to nil (or
495 produce an error) won't be onsidered.
497 * If the snippet has a condition that evaluates to non-nil
500 * If REQUIREMENT is t, the snippet is considered
502 * If REQUIREMENT is `eq' RESULT, the snippet is
505 * Otherwise, the snippet is not considered.
507 * If it evaluates to the symbol 'always, all snippets are
508 considered for expansion, regardless of any conditions.
510 * If it evaluates to t or some other non-nil value
512 * Snippet bearing no conditions, or conditions that
513 evaluate to non-nil, are considered for expansion.
515 * Otherwise, the snippet is not considered.
517 Here's an example preventing snippets from being expanded from
518 inside comments, in `python-mode' only, with the exception of
519 snippets returning the symbol 'force-in-comment in their
522 (add-hook 'python-mode-hook
524 (setq yas/buffer-local-condition
525 '(if (python-in-string/comment)
526 '(require-snippet-condition . force-in-comment)
529 The default value is similar, it filters out potential snippet
530 expansions inside comments and string literals, unless the
531 snippet itself contains a condition that returns the symbol
532 `force-in-comment'.")
535 ;;; Internal variables
537 (defvar yas/version "0.7.0")
539 (defvar yas/menu-table (make-hash-table)
540 "A hash table of MAJOR-MODE symbols to menu keymaps.")
542 (defvar yas/known-modes
543 '(ruby-mode rst-mode markdown-mode)
544 "A list of mode which is well known but not part of emacs.")
546 (defvar yas/escaped-characters
547 '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
548 "List of characters which *might* need to be escaped.")
550 (defconst yas/field-regexp
551 "${\\([0-9]+:\\)?\\([^}]*\\)}"
552 "A regexp to *almost* recognize a field.")
554 (defconst yas/multi-dollar-lisp-expression-regexp
555 "$+[ \t\n]*\\(([^)]*)\\)"
556 "A regexp to *almost* recognize a \"$(...)\" expression.")
558 (defconst yas/backquote-lisp-expression-regexp
560 "A regexp to recognize a \"`lisp-expression`\" expression." )
562 (defconst yas/transform-mirror-regexp
563 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
564 "A regexp to *almost* recognize a mirror with a transform.")
566 (defconst yas/simple-mirror-regexp
568 "A regexp to recognize a simple mirror.")
570 (defvar yas/snippet-id-seed 0
571 "Contains the next id for a snippet.")
573 (defun yas/snippet-next-id ()
574 (let ((id yas/snippet-id-seed))
575 (incf yas/snippet-id-seed)
581 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
582 (defvar last-buffer-undo-list nil)
584 (defvar yas/minor-mode-menu nil
585 "Holds the YASnippet menu")
587 (defun yas/init-minor-keymap ()
588 (let ((map (make-sparse-keymap)))
589 (easy-menu-define yas/minor-mode-menu
591 "Menu used when YAS/minor-mode is active."
594 ["Expand trigger" yas/expand
595 :help "Possibly expand tab trigger before point"]
596 ["Insert at point..." yas/insert-snippet
597 :help "Prompt for an expandable snippet and expand it at point"]
598 ["New snippet..." yas/new-snippet
599 :help "Create a new snippet in an appropriate directory"]
600 ["Visit snippet file..." yas/visit-snippet-file
601 :help "Prompt for an expandable snippet and find its file"]
602 ["Find snippets..." yas/find-snippets
603 :help "Invoke `find-file' in the appropriate snippet directory"]
605 ("Snippet menu behaviour"
606 ["Visit snippets" (setq yas/visit-from-menu t)
607 :help "Visit snippets from the menu"
608 :active t :style radio :selected yas/visit-from-menu]
609 ["Expand snippets" (setq yas/visit-from-menu nil)
610 :help "Expand snippets from the menu"
611 :active t :style radio :selected (not yas/visit-from-menu)]
613 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
614 :help "Show snippet submenus for modes that appear to be real major modes"
615 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
616 ["Show all modes" (setq yas/use-menu 't)
617 :help "Show one snippet submenu for each loaded table"
618 :active t :style radio :selected (eq yas/use-menu 't)]
619 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
620 :help "Show only snippet submenus for the current active modes"
621 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
623 ["Auto" (setq yas/indent-line 'auto)
624 :help "Indent each line of the snippet with `indent-according-to-mode'"
625 :active t :style radio :selected (eq yas/indent-line 'auto)]
626 ["Fixed" (setq yas/indent-line 'fixed)
627 :help "Indent the snippet to the current column"
628 :active t :style radio :selected (eq yas/indent-line 'fixed)]
629 ["None" (setq yas/indent-line 'none)
630 :help "Don't apply any particular snippet indentation after expansion"
631 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
633 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
634 (not yas/also-auto-indent-first-line))
635 :help "When auto-indenting also, auto indent the first line menu"
636 :active (eq yas/indent-line 'auto)
637 :style toggle :selected yas/also-auto-indent-first-line]
640 ["System X-widget" (setq yas/prompt-functions
642 (remove 'yas/x-prompt
643 yas/prompt-functions)))
644 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
645 :active t :style radio :selected (eq (car yas/prompt-functions)
647 ["Dropdown-list" (setq yas/prompt-functions
648 (cons 'yas/dropdown-prompt
649 (remove 'yas/dropdown-prompt
650 yas/prompt-functions)))
651 :help "Use a special dropdown list"
652 :active t :style radio :selected (eq (car yas/prompt-functions)
653 'yas/dropdown-prompt)]
654 ["Ido" (setq yas/prompt-functions
655 (cons 'yas/ido-prompt
656 (remove 'yas/ido-prompt
657 yas/prompt-functions)))
658 :help "Use an ido-style minibuffer prompt"
659 :active t :style radio :selected (eq (car yas/prompt-functions)
661 ["Completing read" (setq yas/prompt-functions
662 (cons 'yas/completing-prompt
663 (remove 'yas/completing-prompt-prompt
664 yas/prompt-functions)))
665 :help "Use a normal minibuffer prompt"
666 :active t :style radio :selected (eq (car yas/prompt-functions)
667 'yas/completing-prompt-prompt)]
670 ["Wrap region in exit marker"
671 (setq yas/wrap-around-region
672 (not yas/wrap-around-region))
673 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
674 :style toggle :selected yas/wrap-around-region]
675 ["Allow stacked expansions "
676 (setq yas/triggers-in-field
677 (not yas/triggers-in-field))
678 :help "If non-nil allow snippets to be triggered inside other snippet fields"
679 :style toggle :selected yas/triggers-in-field]
680 ["Revive snippets on undo "
681 (setq yas/snippet-revival
682 (not yas/snippet-revival))
683 :help "If non-nil allow snippets to become active again after undo"
684 :style toggle :selected yas/snippet-revival]
687 (not yas/good-grace))
688 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
689 :style toggle :selected yas/good-grace]
692 ["Load snippets..." yas/load-directory
693 :help "Load snippets from a specific directory"]
694 ["Reload everything" yas/reload-all
695 :help "Cleanup stuff, reload snippets, rebuild menus"]
697 :help "Display some information about YASsnippet"]))
698 ;; Now for the stuff that has direct keybindings
700 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
701 (define-key map "\C-c&\C-n" 'yas/new-snippet)
702 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
703 (define-key map "\C-c&\C-f" 'yas/find-snippets)
706 (defvar yas/minor-mode-map (yas/init-minor-keymap)
707 "The keymap used when `yas/minor-mode' is active.")
709 (defun yas/trigger-key-reload (&optional unbind-key)
710 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
712 With optional UNBIND-KEY, try to unbind that key from
713 `yas/minor-mode-map'."
714 (when (and unbind-key
716 (not (string= unbind-key "")))
717 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
718 (when (and yas/trigger-key
719 (stringp yas/trigger-key)
720 (not (string= yas/trigger-key "")))
721 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
723 (defvar yas/tables (make-hash-table)
724 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
726 (defvar yas/direct-keymaps (list)
727 "Keymap alist supporting direct snippet keybindings.
729 This variable is is placed `emulation-mode-map-alists'.
731 Its elements looks like (TABLE-NAME . KEYMAP) and are
732 calculated when loading snippets. TABLE-NAME is a variable
733 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
734 all defined direct keybindings to the command
735 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
737 (defun yas/direct-keymaps-reload ()
738 "Force reload the direct keybinding for active snippet tables."
740 (setq yas/direct-keymaps nil)
741 (maphash #'(lambda (name table)
742 (mapc #'(lambda (table)
743 (push (cons (intern (format "yas//direct-%s" name))
744 (yas/table-direct-keymap table))
746 (cons table (yas/table-get-all-parents table))))
749 (defun yas/direct-keymaps-set-vars ()
750 (let ((modes-to-activate (list major-mode))
752 (while (setq mode (get mode 'derived-mode-parent))
753 (push mode modes-to-activate))
754 (dolist (mode (yas/extra-modes))
755 (push mode modes-to-activate))
756 (dolist (mode modes-to-activate)
757 (let ((name (intern (format "yas//direct-%s" mode))))
758 (set-default name nil)
759 (set (make-local-variable name) t)))))
761 (defvar yas/minor-mode-hook nil
762 "Hook run when yas/minor-mode is turned on")
765 (define-minor-mode yas/minor-mode
766 "Toggle YASnippet mode.
768 When YASnippet mode is enabled, the `tas/trigger-key' key expands
769 snippets of code depending on the mode.
771 With no argument, this command toggles the mode.
772 positive prefix argument turns on the mode.
773 Negative prefix argument turns off the mode.
775 You can customize the key through `yas/trigger-key'.
778 \\{yas/minor-mode-map}"
780 ;; The indicator for the mode line.
783 (cond (yas/minor-mode
784 ;; Reload the trigger key
786 (yas/trigger-key-reload)
787 ;; Install the direct keymaps in `emulation-mode-map-alists'
788 ;; (we use `add-hook' even though it's not technically a hook,
789 ;; but it works). Then define variables named after modes to
790 ;; index `yas/direct-keymaps'.
792 ;; Also install the post-command-hook.
794 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
795 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
796 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
798 ;; Uninstall the direct keymaps and the post-command hook
800 (remove-hook 'post-command-hook 'yas/post-command-handler t)
801 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
803 (defun yas/direct-keymaps-set-vars-runonce ()
804 (yas/direct-keymaps-set-vars)
805 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
807 (defvar yas/dont-activate nil
808 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
810 `yas/minor-mode-on' is usually called by `yas/global-mode' so
811 this effectively lets you define exceptions to the \"global\"
812 behaviour. Can also be a function of zero arguments.")
813 (make-variable-buffer-local 'yas/dont-activate)
815 (defun yas/minor-mode-on ()
816 "Turn on YASnippet minor mode.
818 Do this unless `yas/dont-activate' is truish "
820 (unless (or (minibufferp)
821 (if (functionp yas/dont-activate)
822 (funcall yas/dont-activate)
824 ;; Load all snippets definitions unless we still don't have a
825 ;; root-directory or some snippets have already been loaded.
830 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
834 (add-hook 'yas/global-mode-hook 'yas/reload-all-maybe)
835 (defun yas/reload-all-maybe ()
839 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
842 (defvar yas/font-lock-keywords
843 (append '(("^#.*$" . font-lock-comment-face))
844 lisp-font-lock-keywords
845 lisp-font-lock-keywords-1
846 lisp-font-lock-keywords-2
848 (0 font-lock-keyword-face)
849 (1 font-lock-string-face t))
851 (0 font-lock-keyword-face)
852 (1 font-lock-warning-face t))
853 ("${" font-lock-keyword-face)
854 ("$[0-9]+?" font-lock-preprocessor-face)
855 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
857 (0 font-lock-keyword-face)))))
859 (defun yas/init-major-keymap ()
860 (let ((map (make-sparse-keymap)))
861 (easy-menu-define nil
863 "Menu used when snippet-mode is active."
865 (mapcar #'(lambda (ent)
867 (define-key map (third ent) (second ent)))
868 (vector (first ent) (second ent) t))
870 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
871 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
874 (defvar snippet-mode-map
875 (yas/init-major-keymap)
876 "The keymap used when `snippet-mode' is active")
879 (define-derived-mode snippet-mode text-mode "Snippet"
880 "A mode for editing yasnippets"
881 (setq font-lock-defaults '(yas/font-lock-keywords))
882 (set (make-local-variable 'require-final-newline) nil)
883 (set (make-local-variable 'comment-start) "#")
884 (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
888 ;;; Internal structs for template management
890 (defstruct (yas/template (:constructor yas/make-blank-template))
891 "A template for a snippet."
902 group ;; as dictated by the #group: directive or .yas-make-groups
903 perm-group ;; as dictated by `yas/define-menu'
906 (defun yas/populate-template (template &rest args)
907 "Helper function to populate a template with properties"
911 (position (intern (substring (symbol-name (car args)) 1))
912 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
914 (setq args (cddr args)))
917 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
918 "A table to store snippets for a particular mode.
920 Has the following fields:
924 A symbol name normally corresponding to a major mode, but can
925 also be a pseudo major-mode to be referenced in
926 `yas/extra-modes', for example.
930 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
931 a string or a vector, where the former is the snippet's trigger
932 and the latter means it's a direct keybinding. NAMEHASH is yet
933 another hash of (NAME . TEMPLATE) where NAME is the snippet's
934 name and TEMPLATE is a `yas/template' object.
938 A list of tables considered parents of this table: i.e. when
939 searching for expansions they are searched as well.
941 `yas/table-direct-keymap'
943 A keymap for the snippets in this table that have direct
944 keybindings. This is kept in sync with the keyhash, i.e., all
945 the elements of the keyhash that are vectors appear here as
946 bindings to `yas/expand-from-keymap'.
950 A hash table mapping snippets uuid's to the same `yas/template'
951 objects. A snippet uuid defaults to the snippet's name.
954 (hash (make-hash-table :test 'equal))
955 (uuidhash (make-hash-table :test 'equal))
957 (direct-keymap (make-sparse-keymap)))
959 (defun yas/get-template-by-uuid (mode uuid)
960 "Find the snippet template in MODE by its UUID."
961 (let* ((table (gethash mode yas/tables mode)))
963 (gethash uuid (yas/table-uuidhash table)))))
965 ;; Apropos storing/updating, this works with two steps:
967 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
970 ;; 2. `yas/add-template' to add the mappings again:
972 ;; Create or index the entry in TABLES's `yas/table-hash'
973 ;; linking KEY to a namehash. That namehash links NAME to
974 ;; TEMPLATE, and is also created a new namehash inside that
977 (defun yas/remove-template-by-uuid (table uuid)
978 "Remove from TABLE a template identified by UUID."
979 (let ((template (gethash uuid (yas/table-uuidhash table))))
981 (let* ((name (yas/template-name template))
983 ;; Remove the name from each of the targeted namehashes
985 (maphash #'(lambda (k v)
986 (let ((template (gethash name v)))
988 (eq uuid (yas/template-uuid template)))
990 (when (zerop (hash-table-count v))
991 (push k empty-keys)))))
992 (yas/table-hash table))
993 ;; Remove the namehashed themselves if they've become empty
995 (dolist (key empty-keys)
996 (remhash key (yas/table-hash table)))
998 ;; Finally, remove the uuid from the uuidhash
1000 (remhash uuid (yas/table-uuidhash table))))))
1003 (defun yas/add-template (table template)
1004 "Store in TABLE the snippet template TEMPLATE.
1006 KEY can be a string (trigger key) of a vector (direct
1008 (let ((name (yas/template-name template))
1009 (key (yas/template-key template))
1010 (keybinding (yas/template-keybinding template))
1011 (menu-binding (car (yas/template-menu-binding-pair template))))
1012 (dolist (k (remove nil (list key keybinding)))
1016 (yas/table-hash table))
1018 (make-hash-table :test 'equal)
1019 (yas/table-hash table))))
1021 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1024 (setf (getf (cdr menu-binding) :keys)
1025 (or (and keybinding (key-description keybinding))
1026 (and key (concat key yas/trigger-symbol))))
1027 (setcar (cdr menu-binding)
1030 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1032 (defun yas/update-template (snippet-table template)
1033 "Add or update TEMPLATE in SNIPPET-TABLE.
1035 Also takes care of adding and updaring to the associated menu."
1036 ;; Remove from table by uuid
1038 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1039 ;; Add to table again
1041 (yas/add-template snippet-table template)
1042 ;; Take care of the menu
1044 (let ((keymap (yas/menu-keymap-get-create snippet-table))
1045 (group (yas/template-group template)))
1046 (when (and yas/use-menu
1048 (not (cdr (yas/template-menu-binding-pair template))))
1049 ;; Remove from menu keymap
1051 (yas/delete-from-keymap keymap (yas/template-uuid template))
1053 ;; Add necessary subgroups as necessary.
1055 (dolist (subgroup group)
1056 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1057 (unless (and subgroup-keymap
1058 (keymapp subgroup-keymap))
1059 (setq subgroup-keymap (make-sparse-keymap))
1060 (define-key keymap (vector (make-symbol subgroup))
1061 `(menu-item ,subgroup ,subgroup-keymap)))
1062 (setq keymap subgroup-keymap)))
1064 ;; Add this entry to the keymap
1066 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1067 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1069 (defun yas/namehash-templates-alist (namehash)
1071 (maphash #'(lambda (k v)
1072 (push (cons k v) alist))
1076 (defun yas/fetch (table key)
1077 "Fetch templates in TABLE by KEY.
1079 Return a list of cons (NAME . TEMPLATE) where NAME is a
1080 string and TEMPLATE is a `yas/template' structure."
1081 (let* ((keyhash (yas/table-hash table))
1082 (namehash (and keyhash (gethash key keyhash))))
1084 (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
1087 ;;; Filtering/condition logic
1089 (defun yas/eval-condition (condition)
1096 (message (format "[yas] error in condition evaluation: %s"
1097 (error-message-string err)))
1101 (defun yas/filter-templates-by-condition (templates)
1102 "Filter the templates using the applicable condition.
1104 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1105 string and TEMPLATE is a `yas/template' structure.
1107 This function implements the rules described in
1108 `yas/buffer-local-condition'. See that variables documentation."
1109 (let ((requirement (yas/require-template-specific-condition-p)))
1110 (if (eq requirement 'always)
1112 (remove-if-not #'(lambda (pair)
1113 (yas/template-can-expand-p
1114 (yas/template-condition (cdr pair)) requirement))
1117 (defun yas/require-template-specific-condition-p ()
1118 "Decides if this buffer requests/requires snippet-specific
1119 conditions to filter out potential expansions."
1120 (if (eq 'always yas/buffer-local-condition)
1122 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1123 (yas/eval-condition yas/buffer-local-condition))
1124 yas/buffer-local-condition)))
1125 (when local-condition
1126 (if (eq local-condition t)
1128 (and (consp local-condition)
1129 (eq 'require-snippet-condition (car local-condition))
1130 (symbolp (cdr local-condition))
1131 (cdr local-condition)))))))
1133 (defun yas/template-can-expand-p (condition requirement)
1134 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1135 (let* ((result (or (null condition)
1136 (yas/eval-condition condition))))
1137 (cond ((eq requirement t)
1140 (eq requirement result)))))
1142 (defun yas/table-get-all-parents (table)
1143 "Returns a list of all parent tables of TABLE"
1144 (let ((parents (yas/table-parents table)))
1146 (append (copy-list parents)
1147 (mapcan #'yas/table-get-all-parents parents)))))
1149 (defun yas/table-templates (table)
1152 (maphash #'(lambda (key namehash)
1153 (maphash #'(lambda (name template)
1154 (push (cons name template) acc))
1156 (yas/table-hash table))
1157 (yas/filter-templates-by-condition acc))))
1159 (defun yas/current-key ()
1160 "Get the key under current position. A key is used to find
1161 the template of a snippet in the current snippet-table."
1162 (let ((start (point))
1164 (syntaxes yas/key-syntaxes)
1168 (while (and (not done) syntaxes)
1169 (setq syntax (car syntaxes))
1170 (setq syntaxes (cdr syntaxes))
1172 (skip-syntax-backward syntax)
1173 (setq start (point)))
1175 (mapcan #'(lambda (table)
1176 (yas/fetch table (buffer-substring-no-properties start end)))
1177 (yas/get-snippet-tables)))
1186 (defun yas/table-all-keys (table)
1189 (maphash #'(lambda (key namehash)
1190 (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
1192 (yas/table-hash table))
1196 ;;; Internal functions
1198 (defun yas/real-mode? (mode)
1199 "Try to find out if MODE is a real mode. The MODE bound to
1200 a function (like `c-mode') is considered real mode. Other well
1201 known mode like `ruby-mode' which is not part of Emacs might
1202 not bound to a function until it is loaded. So yasnippet keeps
1203 a list of modes like this to help the judgement."
1205 (find mode yas/known-modes)))
1207 (defun yas/eval-lisp (form)
1208 "Evaluate FORM and convert the result to string."
1209 (let ((retval (catch 'yas/exception
1215 (let ((result (eval form)))
1217 (format "%s" result))))))
1218 (error (if yas/good-grace
1219 (format "[yas] elisp error! %s" (error-message-string err))
1220 (error (format "[yas] elisp error: %s"
1221 (error-message-string err)))))))))
1222 (when (and (consp retval)
1223 (eq 'yas/exception (car retval)))
1224 (error (cdr retval)))
1227 (defun yas/eval-lisp-no-saves (form)
1230 (error (if yas/good-grace
1231 (format "[yas] elisp error! %s" (error-message-string err))
1232 (error (format "[yas] elisp error: %s"
1233 (error-message-string err)))))))
1235 (defun yas/read-lisp (string &optional nil-on-error)
1236 "Read STRING as a elisp expression and return it.
1238 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1239 return an expression that when evaluated will issue an error."
1242 (error (and (not nil-on-error)
1243 `(error (error-message-string ,err))))))
1245 (defun yas/read-keybinding (keybinding)
1246 "Read KEYBINDING as a snippet keybinding, return a vector."
1247 (when (and keybinding
1248 (not (string-match "keybinding" keybinding)))
1250 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1252 (read-kbd-macro keybinding 'need-vector))))
1255 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1256 keybinding (error-message-string err))
1259 (defvar yas/extra-modes nil
1260 "If non-nil, also lookup snippets for this/these modes.
1262 Can be a symbol or a list of symbols.
1264 This variable probably makes more sense as buffer-local, so
1265 ensure your use `make-local-variable' when you set it.")
1266 (defun yas/extra-modes ()
1267 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1268 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1270 (defun yas/table-get-create (mode)
1271 "Get the snippet table corresponding to MODE.
1273 Optional DIRECTORY gets recorded as the default directory to
1274 search for snippet files if the retrieved/created table didn't
1275 already have such a property."
1276 (let ((table (gethash mode
1279 (setq table (yas/make-snippet-table (symbol-name mode)))
1280 (puthash mode table yas/tables)
1281 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1282 (yas/table-direct-keymap table)))
1285 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1286 "Get snippet tables for current buffer.
1288 Return a list of 'yas/table' objects indexed by mode.
1290 The modes are tried in this order: optional MODE-SYMBOL, then
1291 `yas/extra-modes', then `major-mode' then, unless
1292 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1293 MODE-SYMBOL or `major-mode'.
1295 Guessing is done by looking up the MODE-SYMBOL's
1296 `derived-mode-parent' property, see also `derived-mode-p'."
1299 (mapcar #'(lambda (mode)
1300 (gethash mode yas/tables))
1301 (remove nil (append (list mode-symbol)
1304 (and (not dont-search-parents)
1306 'derived-mode-parent)))))))))
1309 (mapcan #'yas/table-get-all-parents mode-tables)))))
1311 (defun yas/menu-keymap-get-create (table)
1312 "Get or create the main menu keymap correspondong to MODE.
1314 This may very well create a plethora of menu keymaps and arrange
1315 them in all `yas/menu-table'"
1316 (let* ((mode (intern (yas/table-name table)))
1317 (menu-keymap (or (gethash mode yas/menu-table)
1318 (puthash mode (make-sparse-keymap) yas/menu-table)))
1319 (parents (yas/table-parents table)))
1320 (mapc #'yas/menu-keymap-get-create parents)
1321 (define-key yas/minor-mode-menu (vector mode)
1322 `(menu-item ,(symbol-name mode) ,menu-keymap
1323 :visible (yas/show-menu-p ',mode)))
1326 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1327 ;;; Template-related and snippet loading functions
1329 (defun yas/parse-template (&optional file)
1330 "Parse the template in the current buffer.
1332 Optional FILE is the absolute file name of the file being
1335 Optional GROUP is the group where the template is to go,
1336 otherwise we attempt to calculate it from FILE.
1338 Return a snippet-definition, i.e. a list
1340 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1342 If the buffer contains a line of \"# --\" then the contents above
1343 this line are ignored. Directives can set most of these with the syntax:
1345 # directive-name : directive-value
1347 Here's a list of currently recognized directives:
1358 (goto-char (point-min))
1359 (let* ((type 'snippet)
1361 (file-name-nondirectory file)))
1367 (yas/calculate-group file)))
1371 (if (re-search-forward "^# --\n" nil t)
1372 (progn (setq template
1373 (buffer-substring-no-properties (point)
1375 (setq bound (point))
1376 (goto-char (point-min))
1377 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1378 (when (string= "uuid" (match-string-no-properties 1))
1379 (setq uuid (match-string-no-properties 2)))
1380 (when (string= "type" (match-string-no-properties 1))
1381 (setq type (if (string= "command" (match-string-no-properties 2))
1384 (when (string= "key" (match-string-no-properties 1))
1385 (setq key (match-string-no-properties 2)))
1386 (when (string= "name" (match-string-no-properties 1))
1387 (setq name (match-string-no-properties 2)))
1388 (when (string= "condition" (match-string-no-properties 1))
1389 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1390 (when (string= "group" (match-string-no-properties 1))
1391 (setq group (match-string-no-properties 2)))
1392 (when (string= "expand-env" (match-string-no-properties 1))
1393 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1395 (when (string= "binding" (match-string-no-properties 1))
1396 (setq binding (match-string-no-properties 2)))))
1398 (buffer-substring-no-properties (point-min) (point-max))))
1399 (when (eq type 'command)
1400 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1402 (setq group (split-string group "\\.")))
1403 (list key template name condition group expand-env file binding uuid)))
1405 (defun yas/calculate-group (file)
1406 "Calculate the group for snippet file path FILE."
1407 (let* ((dominating-dir (locate-dominating-file file
1408 ".yas-make-groups"))
1409 (extra-path (and dominating-dir
1410 (replace-regexp-in-string (concat "^"
1411 (expand-file-name dominating-dir))
1413 (expand-file-name file))))
1414 (extra-dir (and extra-path
1415 (file-name-directory extra-path)))
1416 (group (and extra-dir
1417 (replace-regexp-in-string "/"
1419 (directory-file-name extra-dir)))))
1422 (defun yas/subdirs (directory &optional filep)
1423 "Return subdirs or files of DIRECTORY according to FILEP."
1424 (remove-if (lambda (file)
1425 (or (string-match "^\\."
1426 (file-name-nondirectory file))
1427 (string-match "^#.*#$"
1428 (file-name-nondirectory file))
1430 (file-name-nondirectory file))
1432 (file-directory-p file)
1433 (not (file-directory-p file)))))
1434 (directory-files directory t)))
1436 (defun yas/make-menu-binding (template)
1437 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1438 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1440 (defun yas/expand-or-visit-from-menu (mode uuid)
1441 (let* ((table (yas/table-get-create mode))
1442 (yas/current-template (and table
1443 (gethash uuid (yas/table-uuidhash table)))))
1444 (when yas/current-template
1445 (if yas/visit-from-menu
1446 (yas/visit-snippet-file-1 yas/current-template)
1447 (let ((where (if (region-active-p)
1448 (cons (region-beginning) (region-end))
1449 (cons (point) (point)))))
1450 (yas/expand-snippet (yas/template-content yas/current-template)
1453 (yas/template-expand-env yas/current-template)))))))
1455 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1456 ;; Popping up for keys and templates
1458 (defvar yas/x-pretty-prompt-templates nil
1459 "If non-nil, attempt to prompt for templates like TextMate.")
1462 (defun yas/prompt-for-template (templates &optional prompt)
1463 "Interactively choose a template from the list TEMPLATES.
1465 TEMPLATES is a list of `yas/template'."
1468 (sort templates #'(lambda (t1 t2)
1469 (< (length (yas/template-name t1))
1470 (length (yas/template-name t2))))))
1471 (if yas/x-pretty-prompt-templates
1472 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1473 (some #'(lambda (fn)
1474 (funcall fn (or prompt "Choose a snippet: ")
1476 #'yas/template-name))
1477 yas/prompt-functions))))
1479 (defun yas/prompt-for-keys (keys &optional prompt)
1480 "Interactively choose a template key from the list KEYS."
1482 (some #'(lambda (fn)
1483 (funcall fn (or prompt "Choose a snippet key: ") keys))
1484 yas/prompt-functions)))
1486 (defun yas/prompt-for-table (tables &optional prompt)
1488 (some #'(lambda (fn)
1489 (funcall fn (or prompt "Choose a snippet table: ")
1492 yas/prompt-functions)))
1494 (defun yas/x-prompt (prompt choices &optional display-fn)
1495 "Display choices in a x-window prompt."
1496 ;; FIXME: HACK: if we notice that one of the objects in choices is
1497 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1499 ;; This would be better implemented by passing CHOICES as a
1500 ;; strucutred tree rather than a list. Modifications would go as far
1501 ;; up as `yas/all-templates' I think.
1503 (when (and window-system choices)
1505 (let (menu d) ;; d for display
1507 (setq d (or (and display-fn (funcall display-fn c))
1510 (push (cons (concat " " d) c) menu))
1512 (push (car d) menu))))
1513 (setq menu (list prompt (push "title" menu)))
1514 (x-popup-menu (if (fboundp 'posn-at-point)
1515 (let ((x-y (posn-x-y (posn-at-point (point)))))
1516 (list (list (+ (car x-y) 10)
1524 (defun yas/x-pretty-prompt-templates (prompt templates)
1525 "Display TEMPLATES, grouping neatly by table name."
1526 (let ((pretty-alist (list))
1530 (dolist (tl templates)
1531 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1532 (setq more-than-one-table (> (length pretty-alist) 1))
1533 (setq prefix (if more-than-one-table
1535 (dolist (table-and-templates pretty-alist)
1536 (when (cdr table-and-templates)
1537 (if more-than-one-table
1538 (push (yas/table-name (car table-and-templates)) menu))
1539 (dolist (template (cdr table-and-templates))
1540 (push (cons (concat prefix (yas/template-name template))
1542 (setq menu (nreverse menu))
1543 (or (x-popup-menu (if (fboundp 'posn-at-point)
1544 (let ((x-y (posn-x-y (posn-at-point (point)))))
1545 (list (list (+ (car x-y) 10)
1549 (list prompt (push "title" menu)))
1552 (defun yas/ido-prompt (prompt choices &optional display-fn)
1553 (when (featurep 'ido)
1554 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1556 (eval-when-compile (require 'dropdown-list nil t))
1557 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1558 (when (featurep 'dropdown-list)
1559 (let (formatted-choices
1563 (dolist (choice choices)
1564 (setq d (or (and display-fn (funcall display-fn choice))
1567 (push d formatted-choices)
1568 (push choice filtered-choices)))
1570 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1572 (nth n filtered-choices)
1575 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1576 (let (formatted-choices
1580 (completion-fn (or completion-fn
1581 #'completing-read)))
1582 (dolist (choice choices)
1583 (setq d (or (and display-fn (funcall display-fn choice))
1586 (push d formatted-choices)
1587 (push choice filtered-choices)))
1588 (setq chosen (and formatted-choices
1589 (funcall completion-fn prompt
1596 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1598 (defun yas/no-prompt (prompt choices &optional display-fn)
1601 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1602 ;; Loading snippets from files
1604 (defun yas/load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1605 "Recursively load snippet templates from DIRECTORY."
1606 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1607 ;; Load .yas-setup.el files wherever we find them
1609 (load (expand-file-name ".yas-setup" directory) 'noerror)
1610 (if (and (not no-compiled-snippets)
1611 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror))
1612 (message "Loading much faster .yas-compiled-snippets from %s" directory)
1613 (let* ((default-directory directory)
1615 ;; load the snippet files
1618 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1619 (when (file-readable-p file)
1620 (insert-file-contents file nil nil nil t)
1621 (push (yas/parse-template file)
1623 (when (or snippet-defs
1624 (cdr major-mode-and-parents))
1625 (yas/define-snippets mode-sym
1628 ;; now recurse to a lower level
1630 (dolist (subdir (yas/subdirs directory))
1631 (yas/load-directory-1 subdir
1636 (defun yas/load-directory (top-level-dir)
1637 "Load snippet definition from directory hierarchy under TOP-LEVEL-DIR.
1639 Below TOP-LEVEL-DIR., each directory is a mode name."
1640 (interactive "DSelect the root directory: ")
1641 (unless (file-directory-p top-level-dir)
1642 (error "%s is not a directory" top-level-dir))
1643 (unless yas/snippet-dirs
1644 (setq yas/snippet-dirs top-level-dir))
1645 (dolist (dir (yas/subdirs top-level-dir))
1646 (let ((major-mode-and-parents (yas/compute-major-mode-and-parents
1647 (concat dir "/dummy"))))
1648 (yas/load-directory-1 dir
1649 (car major-mode-and-parents)
1650 (cdr major-mode-and-parents))))
1651 (when (interactive-p)
1652 (message "[yas] Loaded snippets from %s." top-level-dir)))
1654 (defun yas/load-snippet-dirs ()
1655 "Reload the directories listed in `yas/snippet-dirs' or
1656 prompt the user to select one."
1658 (if yas/snippet-dirs
1659 (dolist (directory (reverse (yas/snippet-dirs)))
1660 (condition-case oops
1662 (yas/load-directory directory)
1663 (message "[yas] Loaded %s" directory))
1664 (error (push oops errors)
1665 (message "[yas] Check your `yas/snippet-dirs': %s" (second oops)))))
1666 (call-interactively 'yas/load-directory))
1669 (defun yas/reload-all (&optional interactive)
1670 "Reload all snippets and rebuild the YASnippet menu. "
1673 ;; Empty all snippet tables and all menu tables
1675 (setq yas/tables (make-hash-table))
1676 (setq yas/menu-table (make-hash-table))
1678 ;; Init the `yas/minor-mode-map', taking care not to break the
1681 (setf (cdr yas/minor-mode-map)
1682 (cdr (yas/init-minor-keymap)))
1684 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1685 ;; the user to select one.
1687 (setq errors (yas/load-snippet-dirs))
1688 ;; Reload the direct keybindings
1690 (yas/direct-keymaps-reload)
1691 (message "[yas] Reloaded everything...%s." (if errors " (some errors, check *Messages*)" ""))))
1693 (defun yas/quote-string (string)
1694 "Escape and quote STRING.
1695 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1697 (replace-regexp-in-string "[\\\"]"
1702 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1703 ;;; Snippet compilation function
1705 (defun yas/initialize ()
1706 "For backward compatibility, enable `yas/minor-mode' globally"
1707 (yas/global-mode 1))
1709 (defun yas/compile-top-level-dir (top-level-dir)
1710 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR."
1711 (interactive "DTop level snippet directory?")
1712 (dolist (dir (yas/subdirs top-level-dir))
1713 (yas/compile-snippets dir)))
1715 (defun yas/compile-snippets (input-dir &optional output-file)
1716 "Compile snippets files in INPUT-DIR to OUTPUT-FILE file.
1718 Prompts for INPUT-DIR and OUTPUT-FILE if called-interactively"
1719 (interactive (let* ((input-dir (read-directory-name "Snippet dir "))
1720 (output-file (let ((ido-everywhere nil))
1721 (read-file-name "Output file "
1723 ".yas-compiled-snippets.el"
1725 (list input-dir output-file)))
1726 (let ((default-directory input-dir))
1727 (with-temp-file (setq output-file (or output-file ".yas-compiled-snippets.el"))
1728 (flet ((yas/define-snippets
1729 (mode snippets &optional parent-or-parents)
1730 (insert (format ";;; %s - automatically compiled snippets for `%s' , do not edit!\n"
1731 (file-name-nondirectory output-file) mode))
1733 (let ((literal-snippets (list)))
1734 (dolist (snippet snippets)
1735 (let ((key (first snippet))
1736 (template-content (second snippet))
1737 (name (third snippet))
1738 (condition (fourth snippet))
1739 (group (fifth snippet))
1740 (expand-env (sixth snippet))
1741 (file nil) ;; (seventh snippet)) ;; omit on purpose
1742 (binding (eighth snippet))
1743 (uuid (ninth snippet)))
1754 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1756 (insert (format ";;; %s - automatically compiled snippets for `%s' end here\n"
1757 (file-name-nondirectory output-file) mode))
1759 (yas/load-directory-1 input-dir nil nil 'no-compiled-snippets))))
1761 (if (and (called-interactively-p)
1762 (yes-or-no-p (format "Open the resulting file (%s)? "
1763 (expand-file-name output-file))))
1764 (find-file-other-window output-file)))
1768 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1769 ;;; Some user level functions
1774 (message (concat "yasnippet (version "
1776 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1778 (defun yas/define-snippets (mode snippets &optional parent-mode)
1779 "Define SNIPPETS for MODE.
1781 SNIPPETS is a list of snippet definitions, each taking the
1784 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1786 Within these, only KEY and TEMPLATE are actually mandatory.
1788 TEMPLATE might be a lisp form or a string, depending on whether
1789 this is a snippet or a snippet-command.
1791 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1792 been `yas/read-lisp'-ed and will eventually be
1795 The remaining elements are strings.
1797 FILE is probably of very little use if you're programatically
1800 UUID is the snippets \"unique-id\". Loading a second snippet file
1801 with the same uuid replaced the previous snippet.
1803 You can use `yas/parse-template' to return such lists based on
1804 the current buffers contents.
1806 Optional PARENT-MODE can be used to specify the parent tables of
1807 MODE. It can be a mode symbol of a list of mode symbols. It does
1808 not need to be a real mode."
1809 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1810 ;; for the list of snippet tables `parent-tables'.
1812 (let ((snippet-table (yas/table-get-create mode))
1813 (parent-tables (mapcar #'yas/table-get-create
1814 (if (listp parent-mode)
1816 (list parent-mode))))
1818 ;; X) Connect `snippet-table' with `parent-tables'.
1820 ;; TODO: this should be a remove-duplicates of the concatenation
1821 ;; of `snippet-table's existings parents with the new parents...
1823 (dolist (parent parent-tables)
1824 (unless (find parent (yas/table-parents snippet-table))
1826 (yas/table-parents snippet-table))))
1828 ;; X) Now, iterate for evey snippet def list
1830 (dolist (snippet snippets)
1831 (setq template (yas/define-snippets-1 snippet
1835 (defun yas/define-snippets-1 (snippet snippet-table)
1836 "Helper for `yas/define-snippets'."
1837 ;; X) Calculate some more defaults on the values returned by
1838 ;; `yas/parse-template'.
1840 (let* ((file (seventh snippet))
1842 (name (or (third snippet)
1844 (file-name-directory file))))
1845 (condition (fourth snippet))
1846 (group (fifth snippet))
1847 (keybinding (yas/read-keybinding (eighth snippet)))
1848 (uuid (or (ninth snippet)
1850 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1851 (yas/make-blank-template))))
1852 ;; X) populate the template object
1854 (yas/populate-template template
1855 :table snippet-table
1857 :content (second snippet)
1860 :condition condition
1861 :expand-env (sixth snippet)
1862 :file (seventh snippet)
1863 :keybinding keybinding
1865 ;; X) Update this template in the appropriate table. This step
1866 ;; also will take care of adding the key indicators in the
1867 ;; templates menu entry, if any
1869 (yas/update-template snippet-table template)
1870 ;; X) Return the template
1875 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1876 "Get TEMPLATE's menu binding or assign it a new one."
1877 (or (yas/template-menu-binding-pair template)
1878 (let ((key (yas/template-key template))
1879 (keybinding (yas/template-keybinding template)))
1880 (setf (yas/template-menu-binding-pair template)
1881 (cons `(menu-item ,(or (yas/template-name template)
1882 (yas/template-uuid template))
1883 ,(yas/make-menu-binding template)
1887 (defun yas/show-menu-p (mode)
1888 (cond ((eq yas/use-menu 'abbreviate)
1890 (mapcar #'(lambda (table)
1891 (intern (yas/table-name table)))
1892 (yas/get-snippet-tables))))
1893 ((eq yas/use-menu 'real-modes)
1894 (yas/real-mode? mode))
1898 (defun yas/delete-from-keymap (keymap uuid)
1899 "Recursively delete items with UUID from KEYMAP and its submenus."
1901 ;; XXX: This used to skip any submenus named \"parent mode\"
1903 ;; First of all, recursively enter submenus, i.e. the tree is
1904 ;; searched depth first so that stale submenus can be found in the
1907 (mapc #'(lambda (item)
1908 (when (and (listp (cdr item))
1909 (keymapp (third (cdr item))))
1910 (yas/delete-from-keymap (third (cdr item)) uuid)))
1912 ;; Set the uuid entry to nil
1914 (define-key keymap (vector (make-symbol uuid)) nil)
1915 ;; Destructively modify keymap
1917 (setcdr keymap (delete-if #'(lambda (item)
1918 (or (null (cdr item))
1919 (and (keymapp (third (cdr item)))
1920 (null (cdr (third (cdr item)))))))
1923 (defun yas/define-menu (mode menu omit-items)
1924 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
1926 MENU is a list, its elements can be:
1928 - (yas/item UUID) : Creates an entry the snippet identified with
1929 UUID. The menu entry for a snippet thus identified is
1930 permanent, i.e. it will never move in the menu.
1932 - (yas/separator) : Creates a separator
1934 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
1935 SUBMENU has the same form as MENU. NAME is also added to the
1936 list of groups of the snippets defined thereafter.
1938 OMIT-ITEMS is a list of snippet uuid's that will always be
1939 ommited from MODE's menu, even if they're manually loaded.
1941 (let* ((table (yas/table-get-create mode))
1942 (hash (yas/table-uuidhash table)))
1943 (yas/define-menu-1 table
1944 (yas/menu-keymap-get-create table)
1947 (dolist (uuid omit-items)
1948 (let ((template (or (gethash uuid hash)
1949 (yas/populate-template (puthash uuid
1950 (yas/make-blank-template)
1954 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
1956 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
1957 (dolist (e (reverse menu))
1958 (cond ((eq (first e) 'yas/item)
1959 (let ((template (or (gethash (second e) uuidhash)
1960 (yas/populate-template (puthash (second e)
1961 (yas/make-blank-template)
1964 :perm-group group-list
1965 :uuid (second e)))))
1966 (define-key keymap (vector (gensym))
1967 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
1968 ((eq (first e) 'yas/submenu)
1969 (let ((subkeymap (make-sparse-keymap)))
1970 (define-key keymap (vector (gensym))
1971 `(menu-item ,(second e) ,subkeymap))
1972 (yas/define-menu-1 table
1976 (append group-list (list (second e))))))
1977 ((eq (first e) 'yas/separator)
1978 (define-key keymap (vector (gensym))
1979 '(menu-item "----")))
1981 (message "[yas] don't know anything about menu entry %s" (first e))))))
1983 (defun yas/define (mode key template &optional name condition group)
1984 "Define a snippet. Expanding KEY into TEMPLATE.
1986 NAME is a description to this template. Also update the menu if
1987 `yas/use-menu' is `t'. CONDITION is the condition attached to
1988 this snippet. If you attach a condition to a snippet, then it
1989 will only be expanded when the condition evaluated to non-nil."
1990 (yas/define-snippets mode
1991 (list (list key template name condition group))))
1993 (defun yas/hippie-try-expand (first-time?)
1994 "Integrate with hippie expand. Just put this function in
1995 `hippie-expand-try-functions-list'."
1996 (if (not first-time?)
1997 (let ((yas/fallback-behavior 'return-nil))
2003 ;;; Apropos condition-cache:
2008 (defvar yas/condition-cache-timestamp nil)
2009 (defmacro yas/define-condition-cache (func doc &rest body)
2010 "Define a function FUNC with doc DOC and body BODY, BODY is
2011 executed at most once every snippet expansion attempt, to check
2012 expansion conditions.
2014 It doesn't make any sense to call FUNC programatically."
2015 `(defun ,func () ,(if (and doc
2018 "\n\nFor use in snippets' conditions. Within each
2019 snippet-expansion routine like `yas/expand', computes actual
2020 value for the first time then always returns a cached value.")
2021 (setq body (cons doc body))
2023 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2024 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2025 (cdr timestamp-and-value)
2026 (let ((new-value (progn
2029 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2032 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2033 (defun yas/expand-from-trigger-key (&optional field)
2034 "Expand a snippet before point.
2036 If no snippet expansion is possible, fall back to the behaviour
2037 defined in `yas/fallback-behavior'.
2039 Optional argument FIELD is for non-interactive use and is an
2040 object satisfying `yas/field-p' to restrict the expansion to."
2042 (setq yas/condition-cache-timestamp (current-time))
2043 (let (templates-and-pos)
2044 (unless (and yas/expand-only-for-last-commands
2045 (not (member last-command yas/expand-only-for-last-commands)))
2046 (setq templates-and-pos (if field
2048 (narrow-to-region (yas/field-start field)
2049 (yas/field-end field))
2051 (yas/current-key))))
2052 (if (and templates-and-pos
2053 (first templates-and-pos))
2054 (yas/expand-or-prompt-for-template (first templates-and-pos)
2055 (second templates-and-pos)
2056 (third templates-and-pos))
2057 (yas/fallback 'trigger-key))))
2059 (defun yas/expand-from-keymap ()
2060 "Directly expand some snippets, searching `yas/direct-keymaps'.
2062 If expansion fails, execute the previous binding for this key"
2064 (setq yas/condition-cache-timestamp (current-time))
2065 (let* ((yas/prefix current-prefix-arg)
2066 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2067 universal-argument-num-events
2069 (templates (mapcan #'(lambda (table)
2070 (yas/fetch table vec))
2071 (yas/get-snippet-tables))))
2073 (yas/expand-or-prompt-for-template templates)
2074 (let ((yas/fallback-behavior 'call-other-command))
2077 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2078 "Expand one of TEMPLATES from START to END.
2080 Prompt the user if TEMPLATES has more than one element, else
2081 expand immediately. Common gateway for
2082 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2083 (let ((yas/current-template (or (and (rest templates) ;; more than one
2084 (yas/prompt-for-template (mapcar #'cdr templates)))
2086 (when yas/current-template
2087 (yas/expand-snippet (yas/template-content yas/current-template)
2090 (yas/template-expand-env yas/current-template)))))
2092 (defun yas/fallback (&optional from-trigger-key-p)
2093 "Fallback after expansion has failed.
2095 Common gateway for `yas/expand-from-trigger-key' and
2096 `yas/expand-from-keymap'."
2097 (cond ((eq yas/fallback-behavior 'return-nil)
2100 ((eq yas/fallback-behavior 'call-other-command)
2101 (let* ((yas/minor-mode nil)
2102 (yas/direct-keymaps nil)
2103 (keys-1 (this-command-keys-vector))
2104 (keys-2 (and yas/trigger-key
2106 (stringp yas/trigger-key)
2107 (read-kbd-macro yas/trigger-key)))
2108 (command-1 (and keys-1 (key-binding keys-1)))
2109 (command-2 (and keys-2 (key-binding keys-2)))
2110 ;; An (ugly) safety: prevents infinite recursion of
2111 ;; yas/expand* calls.
2112 (command (or (and (symbolp command-1)
2113 (not (string-match "yas/expand" (symbol-name command-1)))
2115 (and (symbolp command-2)
2117 (when (and (commandp command)
2118 (not (string-match "yas/expand" (symbol-name command))))
2119 (setq this-command command)
2120 (call-interactively command))))
2121 ((and (listp yas/fallback-behavior)
2122 (cdr yas/fallback-behavior)
2123 (eq 'apply (car yas/fallback-behavior)))
2124 (if (cddr yas/fallback-behavior)
2125 (apply (cadr yas/fallback-behavior)
2126 (cddr yas/fallback-behavior))
2127 (when (commandp (cadr yas/fallback-behavior))
2128 (setq this-command (cadr yas/fallback-behavior))
2129 (call-interactively (cadr yas/fallback-behavior)))))
2131 ;; also return nil if all the other fallbacks have failed
2136 ;;; Snippet development
2138 (defun yas/all-templates (tables)
2139 "Return all snippet tables applicable for the current buffer.
2141 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2142 `yas/buffer-local-condition'"
2143 (when yas/choose-tables-first
2144 (setq tables (list (yas/prompt-for-table tables))))
2146 (if yas/choose-keys-first
2147 (let ((key (yas/prompt-for-keys
2148 (mapcan #'yas/table-all-keys tables))))
2150 (mapcan #'(lambda (table)
2151 (yas/fetch table key))
2153 (remove-duplicates (mapcan #'yas/table-templates tables)
2156 (defun yas/insert-snippet (&optional no-condition)
2157 "Choose a snippet to expand, pop-up a list of choices according
2158 to `yas/prompt-function'.
2160 With prefix argument NO-CONDITION, bypass filtering of snippets
2163 (setq yas/condition-cache-timestamp (current-time))
2164 (let* ((yas/buffer-local-condition (or (and no-condition
2166 yas/buffer-local-condition))
2167 (templates (yas/all-templates (yas/get-snippet-tables)))
2168 (yas/current-template (and templates
2169 (or (and (rest templates) ;; more than one template for same key
2170 (yas/prompt-for-template templates))
2172 (where (if (region-active-p)
2173 (cons (region-beginning) (region-end))
2174 (cons (point) (point)))))
2175 (if yas/current-template
2176 (yas/expand-snippet (yas/template-content yas/current-template)
2179 (yas/template-expand-env yas/current-template))
2180 (message "[yas] No snippets can be inserted here!"))))
2182 (defun yas/visit-snippet-file ()
2183 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2185 Only success if selected snippet was loaded from a file. Put the
2186 visited file in `snippet-mode'."
2188 (let* ((yas/buffer-local-condition 'always)
2189 (templates (yas/all-templates (yas/get-snippet-tables)))
2190 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2191 (template (and templates
2192 (or (yas/prompt-for-template templates
2193 "Choose a snippet template to edit: ")
2197 (yas/visit-snippet-file-1 template)
2198 (message "No snippets tables active!"))))
2200 (defun yas/visit-snippet-file-1 (template)
2201 (let ((file (yas/template-file template)))
2202 (cond ((and file (file-readable-p file))
2203 (find-file-other-window file)
2205 (set (make-local-variable 'yas/editing-template) template))
2207 (message "Original file %s no longer exists!" file))
2209 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2210 (let ((type 'snippet))
2211 (when (listp (yas/template-content template))
2212 (insert (format "# type: command\n"))
2213 (setq type 'command))
2214 (insert (format "# key: %s\n" (yas/template-key template)))
2215 (insert (format "# name: %s\n" (yas/template-name template)))
2216 (when (yas/template-keybinding template)
2217 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2218 (when (yas/template-expand-env template)
2219 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2220 (when (yas/template-condition template)
2221 (insert (format "# condition: %s\n" (yas/template-condition template))))
2223 (insert (if (eq type 'command)
2224 (pp-to-string (yas/template-content template))
2225 (yas/template-content template))))
2227 (set (make-local-variable 'yas/editing-template) template)))))
2229 (defun yas/guess-snippet-directories-1 (table)
2230 "Guesses possible snippet subdirectories for TABLE."
2231 (cons (yas/table-name table)
2232 (mapcan #'(lambda (parent)
2233 (yas/guess-snippet-directories-1
2235 (yas/table-parents table))))
2237 (defun yas/guess-snippet-directories (&optional table)
2238 "Try to guess suitable directories based on the current active
2239 tables (or optional TABLE).
2241 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2242 `yas/table' object and DIRS is a list of all possible directories
2243 where snippets of table might exist."
2244 (let ((main-dir (replace-regexp-in-string
2246 (or (first (or (yas/snippet-dirs)
2247 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2248 (tables (or (and table
2250 (yas/get-snippet-tables))))
2251 ;; HACK! the snippet table created here is actually registered!
2253 (unless (or table (gethash major-mode yas/tables))
2254 (push (yas/table-get-create major-mode)
2257 (mapcar #'(lambda (table)
2259 (mapcar #'(lambda (subdir)
2260 (concat main-dir "/" subdir))
2261 (yas/guess-snippet-directories-1 table))))
2264 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2265 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2266 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2267 (let ((candidate (first (cdr table-and-dirs))))
2268 (unless (file-writable-p (file-name-directory candidate))
2269 (error "[yas] %s is not writable." candidate))
2270 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2272 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2276 (or main-table-string
2278 (yas/table-name (car table-and-dirs))))
2280 (make-directory candidate 'also-make-parents)
2281 ;; create the .yas-parents file here...
2284 (defun yas/new-snippet (&optional no-template)
2285 "Pops a new buffer for writing a snippet.
2287 Expands a snippet-writing snippet, unless the optional prefix arg
2288 NO-TEMPLATE is non-nil."
2290 (let ((guessed-directories (yas/guess-snippet-directories)))
2292 (switch-to-buffer "*new snippet*")
2294 (kill-all-local-variables)
2297 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2298 (intern (yas/table-name (car d))))
2299 guessed-directories))
2300 (unless no-template (yas/expand-snippet "\
2301 # -*- mode: snippet -*-
2304 # binding: ${4:direct-keybinding}}${5:
2305 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2310 (defun yas/find-snippets (&optional same-window )
2311 "Find snippet file in guessed current mode's directory.
2313 Calls `find-file' interactively in the guessed directory.
2315 With prefix arg SAME-WINDOW opens the buffer in the same window.
2317 Because snippets can be loaded from many different locations,
2318 this has to guess the correct directory using
2319 `yas/guess-snippet-directories', which returns a list of
2322 If any one of these exists, it is taken and `find-file' is called
2323 there, otherwise, proposes to create the first option returned by
2324 `yas/guess-snippet-directories'."
2326 (let* ((guessed-directories (yas/guess-snippet-directories))
2329 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2331 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2332 (mapcar #'(lambda (table-and-dirs)
2333 (yas/table-name (car table-and-dirs)))
2334 (rest guessed-directories))))
2335 (setq chosen (some #'yas/make-directory-maybe
2336 (rest guessed-directories)))))
2338 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2339 (setq chosen (first (yas/snippet-dirs)))))
2341 (let ((default-directory chosen))
2342 (setq buffer (call-interactively (if same-window
2344 'find-file-other-window)))
2348 (when (eq major-mode 'fundamental-mode)
2350 (message "Could not guess snippet dir!"))))
2352 (defun yas/compute-major-mode-and-parents (file)
2353 "Given FILE, find the nearest snippet directory for a given
2354 mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
2355 representing one or more of the mode's parents.
2357 Note that MODE-SYM need not be the symbol of a real major mode,
2358 neither do the elements of PARENTS."
2359 (let* ((file-dir (and file
2360 (directory-file-name (or (some #'(lambda (special)
2361 (locate-dominating-file file special))
2365 (directory-file-name (file-name-directory file))))))
2366 (parents-file-name (concat file-dir "/.yas-parents"))
2367 (major-mode-name (and file-dir
2368 (file-name-nondirectory file-dir)))
2369 (major-mode-sym (or (and major-mode-name
2370 (intern major-mode-name))))
2371 (parents (when (file-readable-p parents-file-name)
2375 (insert-file-contents parents-file-name)
2376 (buffer-substring-no-properties (point-min)
2378 (when major-mode-sym
2379 (cons major-mode-sym parents))))
2381 (defvar yas/editing-template nil
2382 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2384 (defvar yas/current-template nil
2385 "Holds the current template being expanded into a snippet.")
2387 (defvar yas/guessed-modes nil
2388 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2390 (defun yas/load-snippet-buffer (&optional kill)
2391 "Parse and load current buffer's snippet definition.
2393 With optional prefix argument KILL quit the window and buffer."
2396 ;; We have `yas/editing-template', this buffer's
2397 ;; content comes from a template which is already loaded and
2398 ;; neatly positioned,...
2400 (yas/editing-template
2401 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2402 (yas/template-table yas/editing-template)))
2403 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2404 ;; value from `yas/compute-major-mode-and-parents'
2407 (unless yas/guessed-modes
2408 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2409 (let* ((prompt (if (and (featurep 'ido)
2411 'ido-completing-read 'completing-read))
2412 (table (yas/table-get-create
2414 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2415 (if yas/guessed-modes
2416 (first yas/guessed-modes)
2418 (mapcar #'symbol-name yas/guessed-modes)
2423 (if (first yas/guessed-modes)
2424 (symbol-name (first yas/guessed-modes))))))))
2425 (set (make-local-variable 'yas/editing-template)
2426 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2428 ;; Now, offer to save this shit iff:
2430 ;; 1) `yas/snippet-dirs' is a list and its first element does not
2431 ;; match this template's file (i.e. this is a library snippet, not
2432 ;; a user snippet) OR
2434 ;; 2) yas/editing-template comes from a file that we cannot write to...
2436 (when (or (not (yas/template-file yas/editing-template))
2437 (not (file-writable-p (yas/template-file yas/editing-template)))
2438 (and (listp yas/snippet-dirs)
2439 (second yas/snippet-dirs)
2440 (not (string-match (expand-file-name (first yas/snippet-dirs))
2441 (yas/template-file yas/editing-template)))))
2443 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2444 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2446 (yas/make-directory-maybe option))))
2448 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2449 (file-name-nondirectory (yas/template-file yas/editing-template)))
2450 (yas/template-name yas/editing-template))))
2451 (write-file (concat chosen "/"
2452 (read-from-minibuffer (format "File name to create in %s? " chosen)
2453 default-file-name)))
2454 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2457 (message "[yas] Snippet \"%s\" loaded for %s."
2458 (yas/template-name yas/editing-template)
2459 (yas/table-name (yas/template-table yas/editing-template))))
2462 (defun yas/tryout-snippet (&optional debug)
2463 "Test current buffers's snippet template in other buffer."
2465 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2466 (parsed (yas/parse-template))
2467 (test-mode (or (and (car major-mode-and-parent)
2468 (fboundp (car major-mode-and-parent))
2469 (car major-mode-and-parent))
2470 (first yas/guessed-modes)
2471 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2472 (yas/current-template
2475 (yas/populate-template (yas/make-blank-template)
2476 :table nil ;; no tables for ephemeral snippets
2478 :content (second parsed)
2479 :name (third parsed)
2480 :expand-env (sixth parsed)))))
2481 (cond (yas/current-template
2482 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2483 (kill-buffer (get-buffer-create buffer-name))
2484 (switch-to-buffer (get-buffer-create buffer-name))
2485 (setq buffer-undo-list nil)
2486 (condition-case nil (funcall test-mode) (error nil))
2487 (setq buffer-read-only nil)
2488 (yas/expand-snippet (yas/template-content yas/current-template)
2491 (yas/template-expand-env yas/current-template))
2493 (require 'yasnippet-debug nil t))
2494 (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
2496 (message "[yas] Cannot test snippet for unknown major mode")))))
2498 (defun yas/template-fine-group (template)
2499 (car (last (or (yas/template-group template)
2500 (yas/template-perm-group template)))))
2502 (defun yas/describe-tables (&optional choose)
2503 "Display snippets for each table."
2505 (let* ((by-name-hash (and choose
2506 (y-or-n-p "Show by namehash? ")))
2507 (buffer (get-buffer-create "*YASnippet tables*"))
2508 (active-tables (yas/get-snippet-tables))
2509 (remain-tables (let ((all))
2510 (maphash #'(lambda (k v)
2511 (unless (find v active-tables)
2515 (table-lists (list active-tables remain-tables))
2516 (original-buffer (current-buffer))
2518 (yas/condition-cache-timestamp (current-time)))
2519 (with-current-buffer buffer
2520 (setq buffer-read-only nil)
2522 (cond ((not by-name-hash)
2523 (insert "YASnippet tables: \n")
2524 (while (and table-lists
2526 (dolist (table (car table-lists))
2527 (yas/describe-pretty-table table original-buffer))
2528 (setq table-lists (cdr table-lists))
2530 (yas/create-snippet-xrefs)
2531 (display-buffer buffer)
2532 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2533 (yas/create-snippet-xrefs)
2537 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2538 (dolist (table (append active-tables remain-tables))
2539 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2541 (maphash #'(lambda (k v)
2543 (yas/table-hash table))
2545 (insert (format " key %s maps snippets: %s\n" key
2547 (maphash #'(lambda (k v)
2549 (gethash key (yas/table-hash table)))
2552 (setq buffer-read-only t))
2553 (display-buffer buffer)))
2555 (defun yas/describe-pretty-table (table &optional original-buffer)
2556 (insert (format "\nSnippet table `%s'"
2557 (yas/table-name table)))
2558 (if (yas/table-parents table)
2559 (insert (format " parents: %s\n"
2560 (mapcar #'yas/table-name
2561 (yas/table-parents table))))
2563 (insert (make-string 100 ?-) "\n")
2564 (insert "group state name key binding\n")
2565 (let ((groups-alist (list))
2567 (maphash #'(lambda (k v)
2568 (setq group (or (yas/template-fine-group v)
2570 (when (yas/template-name v)
2572 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2573 (yas/table-uuidhash table))
2574 (dolist (group-and-templates groups-alist)
2575 (when (rest group-and-templates)
2576 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2577 (insert (make-string 100 ?-) "\n")
2578 (dolist (p (cdr group-and-templates))
2579 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2583 (setq group (make-string (length group) ? ))))
2584 (condition-string (let ((condition (yas/template-condition p)))
2587 (with-current-buffer original-buffer
2588 (if (yas/eval-condition condition)
2593 (insert condition-string " ")
2595 (if (string-match "\\.\\.\\.$" name)
2599 (insert (truncate-string-to-width (or (yas/template-key p) "")
2601 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2609 ;;; User convenience functions, for using in snippet definitions
2611 (defvar yas/modified-p nil
2612 "Non-nil if field has been modified by user or transformation.")
2614 (defvar yas/moving-away-p nil
2615 "Non-nil if user is about to exit field.")
2617 (defvar yas/text nil
2618 "Contains current field text.")
2620 (defun yas/substr (str pattern &optional subexp)
2621 "Search PATTERN in STR and return SUBEXPth match.
2623 If found, the content of subexp group SUBEXP (default 0) is
2624 returned, or else the original STR will be returned."
2625 (let ((grp (or subexp 0)))
2627 (if (string-match pattern str)
2628 (match-string-no-properties grp str)
2631 (defun yas/choose-value (possibilities)
2632 "Prompt for a string in the list POSSIBILITIES and return it."
2633 (unless (or yas/moving-away-p
2635 (some #'(lambda (fn)
2636 (funcall fn "Choose: " possibilities))
2637 yas/prompt-functions)))
2639 (defun yas/key-to-value (alist)
2640 "Prompt for a string in the list POSSIBILITIES and return it."
2641 (unless (or yas/moving-away-p
2643 (let ((key (read-key-sequence "")))
2645 (or (cdr (find key alist :key #'car :test #'string=))
2648 (defun yas/throw (text)
2649 "Throw a yas/exception with TEXT as the reason."
2650 (throw 'yas/exception (cons 'yas/exception text)))
2652 (defun yas/verify-value (possibilities)
2653 "Verify that the current field value is in POSSIBILITIES
2655 Otherwise throw exception."
2656 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2657 (yas/throw (format "[yas] field only allows %s" possibilities))))
2659 (defun yas/field-value (number)
2660 "Get the string for field with NUMBER.
2662 Use this in primary and mirror transformations to tget."
2663 (let* ((snippet (car (yas/snippets-at-point)))
2665 (yas/snippet-find-field snippet number))))
2667 (yas/field-text-for-display field))))
2670 "Return `yas/text' if that exists and is non-empty, else nil."
2672 (not (string= "" yas/text)))
2675 ;; (defun yas/selected-text ()
2676 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2677 ;; (if (and yas/selected-text
2678 ;; (not (string= "" yas/selected-text)))
2679 ;; yas/selected-text))
2681 (defun yas/get-field-once (number &optional transform-fn)
2682 (unless yas/modified-p
2684 (funcall transform-fn (yas/field-value number))
2685 (yas/field-value number))))
2687 (defun yas/default-from-field (number)
2688 (unless yas/modified-p
2689 (yas/field-value number)))
2691 (defun yas/inside-string ()
2692 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2694 (defun yas/unimplemented (&optional missing-feature)
2695 (if yas/current-template
2696 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2699 (yas/visit-snippet-file-1 yas/current-template))
2700 (message "No implementation. Missing %s" (or missing-feature "something"))))
2703 ;;; Snippet expansion and field management
2705 (defvar yas/active-field-overlay nil
2706 "Overlays the currently active field.")
2708 (defvar yas/field-protection-overlays nil
2709 "Two overlays protect the current active field ")
2711 (defconst yas/prefix nil
2712 "A prefix argument for expansion direct from keybindings")
2714 (defvar yas/selected-text nil
2715 "The selected region deleted on the last snippet expansion.")
2717 (defvar yas/start-column nil
2718 "The column where the snippet expansion started.")
2720 (make-variable-buffer-local 'yas/active-field-overlay)
2721 (make-variable-buffer-local 'yas/field-protection-overlays)
2722 (put 'yas/active-field-overlay 'permanent-local t)
2723 (put 'yas/field-protection-overlays 'permanent-local t)
2725 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2731 (id (yas/snippet-next-id) :read-only t)
2732 (control-overlay nil)
2734 ;; stacked expansion: the `previous-active-field' slot saves the
2735 ;; active field where the child expansion took place
2736 previous-active-field
2739 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2749 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2756 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2760 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2761 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2763 If there is no transform for ht field, return nil.
2765 If there is a transform but it returns nil, return the empty
2766 string iff EMPTY-ON-NIL-P is true."
2767 (let* ((yas/text (yas/field-text-for-display field))
2769 (yas/modified-p (yas/field-modified-p field))
2770 (yas/moving-away-p nil)
2771 (transform (if (yas/mirror-p field-or-mirror)
2772 (yas/mirror-transform field-or-mirror)
2773 (yas/field-transform field-or-mirror)))
2774 (start-point (if (yas/mirror-p field-or-mirror)
2775 (yas/mirror-start field-or-mirror)
2776 (yas/field-start field-or-mirror)))
2777 (transformed (and transform
2779 (goto-char start-point)
2780 (let ((ret (yas/eval-lisp transform)))
2781 (or ret (and empty-on-nil-p "")))))))
2784 (defsubst yas/replace-all (from to &optional text)
2785 "Replace all occurance from FROM to TO.
2787 With optional string TEXT do it in that string."
2789 (replace-regexp-in-string (regexp-quote from) to text t t)
2790 (goto-char (point-min))
2791 (while (search-forward from nil t)
2792 (replace-match to t t text))))
2794 (defun yas/snippet-find-field (snippet number)
2795 (find-if #'(lambda (field)
2796 (eq number (yas/field-number field)))
2797 (yas/snippet-fields snippet)))
2799 (defun yas/snippet-sort-fields (snippet)
2800 "Sort the fields of SNIPPET in navigation order."
2801 (setf (yas/snippet-fields snippet)
2802 (sort (yas/snippet-fields snippet)
2803 #'yas/snippet-field-compare)))
2805 (defun yas/snippet-field-compare (field1 field2)
2806 "Compare two fields. The field with a number is sorted first.
2807 If they both have a number, compare through the number. If neither
2808 have, compare through the field's start point"
2809 (let ((n1 (yas/field-number field1))
2810 (n2 (yas/field-number field2)))
2813 (or (zerop n2) (and (not (zerop n1))
2818 (< (yas/field-start field1)
2819 (yas/field-start field2))))))
2821 (defun yas/field-probably-deleted-p (snippet field)
2822 "Guess if SNIPPET's FIELD should be skipped."
2823 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2824 (or (yas/field-parent-field field)
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
2829 (not (zerop (yas/field-number field)))))
2831 (defun yas/snippets-at-point (&optional all-snippets)
2832 "Return a sorted list of snippets at point, most recently
2835 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2836 (overlay-get ov 'yas/snippet))
2838 (overlays-in (point-min) (point-max))
2839 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2841 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2843 (defun yas/next-field-or-maybe-expand ()
2844 "Try to expand a snippet at a key before point, otherwise
2845 delegate to `yas/next-field'."
2847 (if yas/triggers-in-field
2848 (let ((yas/fallback-behavior 'return-nil)
2849 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2851 (unless (yas/expand-from-trigger-key active-field)
2855 (defun yas/next-field (&optional arg)
2856 "Navigate to next field. If there's none, exit the snippet."
2860 (snippet (first (yas/snippets-at-point)))
2861 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2862 (live-fields (remove-if #'(lambda (field)
2863 (and (not (eq field active-field))
2864 (yas/field-probably-deleted-p snippet field)))
2865 (yas/snippet-fields snippet)))
2866 (active-field-pos (position active-field live-fields))
2867 (target-pos (and active-field-pos (+ arg active-field-pos)))
2868 (target-field (and target-pos (nth target-pos live-fields))))
2869 ;; First check if we're moving out of a field with a transform
2871 (when (and active-field
2872 (yas/field-transform active-field))
2873 (let* ((yas/moving-away-p t)
2874 (yas/text (yas/field-text-for-display active-field))
2876 (yas/modified-p (yas/field-modified-p active-field)))
2877 ;; primary field transform: exit call to field-transform
2878 (yas/eval-lisp (yas/field-transform active-field))))
2879 ;; Now actually move...
2880 (cond ((and target-pos (>= target-pos (length live-fields)))
2881 (yas/exit-snippet snippet))
2883 (yas/move-to-field snippet target-field))
2887 (defun yas/place-overlays (snippet field)
2888 "Correctly place overlays for SNIPPET's FIELD"
2889 (yas/make-move-field-protection-overlays snippet field)
2890 (yas/make-move-active-field-overlay snippet field))
2892 (defun yas/move-to-field (snippet field)
2893 "Update SNIPPET to move to field FIELD.
2895 Also create some protection overlays"
2896 (goto-char (yas/field-start field))
2897 (yas/place-overlays snippet field)
2898 (overlay-put yas/active-field-overlay 'yas/field field)
2899 (let ((number (yas/field-number field)))
2900 ;; check for the special ${0: ...} field
2901 (if (and number (zerop number))
2903 (set-mark (yas/field-end field))
2904 (setf (yas/snippet-force-exit snippet)
2905 (or (yas/field-transform field)
2907 ;; make this field active
2908 (setf (yas/snippet-active-field snippet) field)
2909 ;; primary field transform: first call to snippet transform
2910 (unless (yas/field-modified-p field)
2911 (if (yas/field-update-display field snippet)
2912 (yas/update-mirrors snippet)
2913 (setf (yas/field-modified-p field) nil))))))
2915 (defun yas/prev-field ()
2916 "Navigate to prev field. If there's none, exit the snippet."
2918 (yas/next-field -1))
2920 (defun yas/abort-snippet (&optional snippet)
2922 (let ((snippet (or snippet
2923 (car (yas/snippets-at-point)))))
2925 (setf (yas/snippet-force-exit snippet) t))))
2927 (defun yas/exit-snippet (snippet)
2928 "Goto exit-marker of SNIPPET."
2929 (interactive (list (first (yas/snippets-at-point))))
2931 (setf (yas/snippet-force-exit snippet) t)
2932 (goto-char (if (yas/snippet-exit snippet)
2933 (yas/exit-marker (yas/snippet-exit snippet))
2934 (overlay-end (yas/snippet-control-overlay snippet))))))
2936 (defun yas/exit-all-snippets ()
2937 "Exit all snippets."
2939 (mapc #'(lambda (snippet)
2940 (yas/exit-snippet snippet)
2941 (yas/check-commit-snippet))
2942 (yas/snippets-at-point)))
2945 ;;; Some low level snippet-routines
2947 (defmacro yas/inhibit-overlay-hooks (&rest body)
2948 "Run BODY with `yas/inhibit-overlay-hooks' set to t."
2949 (declare (indent 0))
2950 `(let ((yas/inhibit-overlay-hooks t))
2953 (defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
2954 (defvar yas/snippet-end nil "End position of the last snippet commited.")
2956 (defun yas/commit-snippet (snippet)
2957 "Commit SNIPPET, but leave point as it is. This renders the
2958 snippet as ordinary text."
2960 (let ((control-overlay (yas/snippet-control-overlay snippet)))
2962 ;; Save the end of the moribund snippet in case we need to revive it
2963 ;; its original expansion.
2965 (when (and control-overlay
2966 (overlay-buffer control-overlay))
2967 (setq yas/snippet-beg (overlay-start control-overlay))
2968 (setq yas/snippet-end (overlay-end control-overlay))
2969 (delete-overlay control-overlay))
2971 (yas/inhibit-overlay-hooks
2972 (when yas/active-field-overlay
2973 (delete-overlay yas/active-field-overlay))
2974 (when yas/field-protection-overlays
2975 (mapc #'delete-overlay yas/field-protection-overlays)))
2977 ;; stacked expansion: if the original expansion took place from a
2978 ;; field, make sure we advance it here at least to
2979 ;; `yas/snippet-end'...
2981 (let ((previous-field (yas/snippet-previous-active-field snippet)))
2982 (when (and yas/snippet-end previous-field)
2983 (yas/advance-end-maybe previous-field yas/snippet-end)))
2985 ;; Convert all markers to points,
2987 (yas/markers-to-points snippet)
2989 ;; Take care of snippet revival
2991 (if yas/snippet-revival
2992 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
2994 ;; Dismember the snippet... this is useful if we get called
2995 ;; again from `yas/take-care-of-redo'....
2996 (setf (yas/snippet-fields snippet) nil)))
2998 (message "[yas] snippet %s exited." (yas/snippet-id snippet)))
3000 (defun yas/safely-run-hooks (hook-var)
3001 (condition-case error
3002 (run-hooks hook-var)
3004 (message "[yas] %s error: %s" hook-var (error-message-string error)))))
3007 (defun yas/check-commit-snippet ()
3008 "Checks if point exited the currently active field of the
3009 snippet, if so cleans up the whole snippet up."
3010 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3011 (snippets-left snippets)
3012 (snippet-exit-transform))
3013 (dolist (snippet snippets)
3014 (let ((active-field (yas/snippet-active-field snippet)))
3015 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3016 (cond ((or snippet-exit-transform
3017 (not (and active-field (yas/field-contains-point-p active-field))))
3018 (setq snippets-left (delete snippet snippets-left))
3019 (setf (yas/snippet-force-exit snippet) nil)
3020 (yas/commit-snippet snippet))
3022 (or (not yas/active-field-overlay)
3023 (not (overlay-buffer yas/active-field-overlay))))
3025 ;; stacked expansion: this case is mainly for recent
3026 ;; snippet exits that place us back int the field of
3030 (yas/move-to-field snippet active-field)
3031 (yas/update-mirrors snippet)))
3034 (unless (or (null snippets) snippets-left)
3035 (if snippet-exit-transform
3036 (yas/eval-lisp-no-saves snippet-exit-transform))
3037 (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
3039 ;; Apropos markers-to-points:
3041 ;; This was found useful for performance reasons, so that an
3042 ;; excessive number of live markers aren't kept around in the
3043 ;; `buffer-undo-list'. However, in `markers-to-points', the
3044 ;; set-to-nil markers can't simply be discarded and replaced with
3045 ;; fresh ones in `points-to-markers'. The original marker that was
3046 ;; just set to nil has to be reused.
3048 ;; This shouldn't bring horrible problems with undo/redo, but it
3051 (defun yas/markers-to-points (snippet)
3052 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3053 where POINT is the original position of the marker and MARKER is
3054 the original marker object with the position set to nil."
3055 (dolist (field (yas/snippet-fields snippet))
3056 (let ((start (marker-position (yas/field-start field)))
3057 (end (marker-position (yas/field-end field))))
3058 (set-marker (yas/field-start field) nil)
3059 (set-marker (yas/field-end field) nil)
3060 (setf (yas/field-start field) (cons start (yas/field-start field)))
3061 (setf (yas/field-end field) (cons end (yas/field-end field))))
3062 (dolist (mirror (yas/field-mirrors field))
3063 (let ((start (marker-position (yas/mirror-start mirror)))
3064 (end (marker-position (yas/mirror-end mirror))))
3065 (set-marker (yas/mirror-start mirror) nil)
3066 (set-marker (yas/mirror-end mirror) nil)
3067 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3068 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3069 (let ((snippet-exit (yas/snippet-exit snippet)))
3071 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3072 (set-marker (yas/exit-marker snippet-exit) nil)
3073 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3075 (defun yas/points-to-markers (snippet)
3076 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3077 is done by setting MARKER to POINT with `set-marker'."
3078 (dolist (field (yas/snippet-fields snippet))
3079 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3080 (car (yas/field-start field))))
3081 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3082 (car (yas/field-end field))))
3083 (dolist (mirror (yas/field-mirrors field))
3084 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3085 (car (yas/mirror-start mirror))))
3086 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3087 (car (yas/mirror-end mirror))))))
3088 (let ((snippet-exit (yas/snippet-exit snippet)))
3090 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3091 (car (yas/exit-marker snippet-exit)))))))
3093 (defun yas/field-contains-point-p (field &optional point)
3094 (let ((point (or point
3096 (and (>= point (yas/field-start field))
3097 (<= point (yas/field-end field)))))
3099 (defun yas/field-text-for-display (field)
3100 "Return the propertized display text for field FIELD. "
3101 (buffer-substring (yas/field-start field) (yas/field-end field)))
3103 (defun yas/undo-in-progress ()
3104 "True if some kind of undo is in progress"
3105 (or undo-in-progress
3106 (eq this-command 'undo)
3107 (eq this-command 'redo)))
3109 (defun yas/make-control-overlay (snippet start end)
3110 "Creates the control overlay that surrounds the snippet and
3112 (let ((overlay (make-overlay start
3117 (overlay-put overlay 'keymap yas/keymap)
3118 (overlay-put overlay 'priority 100)
3119 (overlay-put overlay 'yas/snippet snippet)
3122 (defun yas/skip-and-clear-or-delete-char (&optional field)
3123 "Clears unmodified field if at field start, skips to next tab.
3125 Otherwise deletes a character normally by calling `delete-char'."
3127 (let ((field (or field
3128 (and yas/active-field-overlay
3129 (overlay-buffer yas/active-field-overlay)
3130 (overlay-get yas/active-field-overlay 'yas/field)))))
3132 (not (yas/field-modified-p field))
3133 (eq (point) (marker-position (yas/field-start field))))
3134 (yas/skip-and-clear field)
3137 (call-interactively 'delete-char)))))
3139 (defun yas/skip-and-clear (field)
3140 "Deletes the region of FIELD and sets it modified state to t"
3141 ;; Just before skipping-and-clearing the field, mark its children
3142 ;; fields as modified, too. If the childen have mirrors-in-fields
3143 ;; this prevents them from updating erroneously (we're skipping and
3146 (yas/mark-this-and-children-modified field)
3147 (delete-region (yas/field-start field) (yas/field-end field)))
3149 (defun yas/mark-this-and-children-modified (field)
3150 (setf (yas/field-modified-p field) t)
3151 (let ((fom (yas/field-next field)))
3153 (yas/fom-parent-field fom))
3154 (when (and (eq (yas/fom-parent-field fom) field)
3156 (yas/mark-this-and-children-modified fom))
3157 (setq fom (yas/fom-next fom)))))
3159 (defun yas/make-move-active-field-overlay (snippet field)
3160 "Place the active field overlay in SNIPPET's FIELD.
3162 Move the overlay, or create it if it does not exit."
3163 (if (and yas/active-field-overlay
3164 (overlay-buffer yas/active-field-overlay))
3165 (move-overlay yas/active-field-overlay
3166 (yas/field-start field)
3167 (yas/field-end field))
3168 (setq yas/active-field-overlay
3169 (make-overlay (yas/field-start field)
3170 (yas/field-end field)
3172 (overlay-put yas/active-field-overlay 'priority 100)
3173 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3174 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3175 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3176 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3177 '(yas/on-field-overlay-modification))
3178 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3179 '(yas/on-field-overlay-modification))))
3181 (defvar yas/inhibit-overlay-hooks nil
3182 "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
3184 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3185 "Clears the field and updates mirrors, conditionally.
3187 Only clears the field if it hasn't been modified and it point it
3188 at field start. This hook doesn't do anything if an undo is in
3190 (unless (or yas/inhibit-overlay-hooks
3191 (yas/undo-in-progress))
3192 (let* ((field (overlay-get overlay 'yas/field))
3193 (number (and field (yas/field-number field)))
3194 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3196 (yas/advance-end-maybe field (overlay-end overlay))
3198 (yas/field-update-display field snippet))
3199 (yas/update-mirrors snippet))
3201 (when (and (not after?)
3202 (not (yas/field-modified-p field))
3203 (eq (point) (if (markerp (yas/field-start field))
3204 (marker-position (yas/field-start field))
3205 (yas/field-start field))))
3206 (yas/skip-and-clear field))
3207 (setf (yas/field-modified-p field) t))))))
3209 ;;; Apropos protection overlays:
3211 ;; These exist for nasty users who will try to delete parts of the
3212 ;; snippet outside the active field. Actual protection happens in
3213 ;; `yas/on-protection-overlay-modification'.
3215 ;; Currently this signals an error which inhibits the command. For
3216 ;; commands that move point (like `kill-line'), point is restored in
3217 ;; the `yas/post-command-handler' using a global
3218 ;; `yas/protection-violation' variable.
3220 ;; Alternatively, I've experimented with an implementation that
3221 ;; commits the snippet before actually calling `this-command'
3222 ;; interactively, and then signals an eror, which is ignored. but
3223 ;; blocks all other million modification hooks. This presented some
3224 ;; problems with stacked expansion.
3227 (defun yas/make-move-field-protection-overlays (snippet field)
3228 "Place protection overlays surrounding SNIPPET's FIELD.
3230 Move the overlays, or create them if they do not exit."
3231 (let ((start (yas/field-start field))
3232 (end (yas/field-end field)))
3233 ;; First check if the (1+ end) is contained in the buffer,
3234 ;; otherwise we'll have to do a bit of cheating and silently
3235 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3236 ;; when using stacked expansion
3238 (when (< (buffer-size) end)
3240 (yas/inhibit-overlay-hooks
3241 (goto-char (point-max))
3243 ;; go on to normal overlay creation/moving
3245 (cond ((and yas/field-protection-overlays
3246 (every #'overlay-buffer yas/field-protection-overlays))
3247 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3248 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3250 (setq yas/field-protection-overlays
3251 (list (make-overlay (1- start) start nil t nil)
3252 (make-overlay end (1+ end) nil t nil)))
3253 (dolist (ov yas/field-protection-overlays)
3254 (overlay-put ov 'face 'yas/field-debug-face)
3255 (overlay-put ov 'yas/snippet snippet)
3256 ;; (overlay-put ov 'evaporate t)
3257 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3259 (defvar yas/protection-violation nil
3260 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3262 Functions in the `post-command-hook', for example
3263 `yas/post-command-handler' can check it and reset its value to
3264 nil. The variables value is the point where the violation
3267 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3268 "Signals a snippet violation, then issues error.
3270 The error should be ignored in `debug-ignored-errors'"
3271 (unless yas/inhibit-overlay-hooks
3272 (cond ((not (or after?
3273 (yas/undo-in-progress)))
3274 (setq yas/protection-violation (point))
3275 (error "Exit the snippet first!")))))
3277 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3280 ;;; Apropos stacked expansion:
3282 ;; the parent snippet does not run its fields modification hooks
3283 ;; (`yas/on-field-overlay-modification' and
3284 ;; `yas/on-protection-overlay-modification') while the child snippet
3285 ;; is active. This means, among other things, that the mirrors of the
3286 ;; parent snippet are not updated, this only happening when one exits
3287 ;; the child snippet.
3289 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3290 ;; bits of code in `yas/expand-snippet' and
3291 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3294 ;; This was thought to be safer in in an undo/redo perpective, but
3295 ;; maybe the correct implementation is to make the globals
3296 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3297 ;; snippet-local and be active even while the child snippet is
3298 ;; running. This would mean a lot of overlay modification hooks
3299 ;; running, but if managed correctly (including overlay priorities)
3300 ;; they should account for all situations...
3303 (defun yas/expand-snippet (content &optional start end expand-env)
3304 "Expand snippet CONTENT at current point.
3306 Text between START and END will be deleted before inserting
3307 template. EXPAND-ENV is are let-style variable to value bindings
3308 considered when expanding the snippet."
3309 (run-hooks 'yas/before-expand-snippet-hook)
3311 ;; If a region is active, set `yas/selected-text'
3312 (setq yas/selected-text
3313 (when (region-active-p)
3314 (prog1 (buffer-substring-no-properties (region-beginning)
3316 (unless start (setq start (region-beginning))
3317 (unless end (setq end (region-end)))))))
3323 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3324 (start (or start (point)))
3325 (end (or end (point)))
3327 (setq yas/indent-original-column (current-column))
3328 ;; Delete the region to delete, this *does* get undo-recorded.
3330 (when (and to-delete
3332 (delete-region start end))
3334 (cond ((listp content)
3335 ;; x) This is a snippet-command
3337 (yas/eval-lisp-no-saves content))
3339 ;; x) This is a snippet-snippet :-)
3341 ;; Narrow the region down to the content, shoosh the
3342 ;; `buffer-undo-list', and create the snippet, the new
3343 ;; snippet updates its mirrors once, so we are left with
3344 ;; some plain text. The undo action for deleting this
3345 ;; plain text will get recorded at the end.
3347 ;; stacked expansion: also shoosh the overlay modification hooks
3349 (narrow-to-region start start)
3350 (let ((buffer-undo-list t))
3351 ;; snippet creation might evaluate users elisp, which
3352 ;; might generate errors, so we have to be ready to catch
3353 ;; them mostly to make the undo information
3355 (setq yas/start-column (save-restriction (widen) (current-column)))
3356 (yas/inhibit-overlay-hooks
3359 (eval `(let* ,expand-env
3361 (yas/snippet-create (point-min) (point-max))))
3363 (yas/snippet-create (point-min) (point-max)))))))
3365 ;; stacked-expansion: This checks for stacked expansion, save the
3366 ;; `yas/previous-active-field' and advance its boudary.
3368 (let ((existing-field (and yas/active-field-overlay
3369 (overlay-buffer yas/active-field-overlay)
3370 (overlay-get yas/active-field-overlay 'yas/field))))
3371 (when existing-field
3372 (setf (yas/snippet-previous-active-field snippet) existing-field)
3373 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3375 ;; Exit the snippet immediately if no fields
3377 (unless (yas/snippet-fields snippet)
3378 (yas/exit-snippet snippet))
3380 ;; Push two undo actions: the deletion of the inserted contents of
3381 ;; the new snippet (without the "key") followed by an apply of
3382 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3384 ;; A small exception, if `yas/also-auto-indent-first-line'
3385 ;; is t and `yas/indent' decides to indent the line to a
3386 ;; point before the actual expansion point, undo would be
3387 ;; messed up. We call the early point "newstart"". case,
3388 ;; and attempt to fix undo.
3390 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3391 (end (overlay-end (yas/snippet-control-overlay snippet))))
3392 (when (< newstart start)
3393 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3394 (push (cons newstart end) buffer-undo-list)
3395 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3397 ;; Now, schedule a move to the first field
3399 (let ((first-field (car (yas/snippet-fields snippet))))
3401 (sit-for 0) ;; fix issue 125
3402 (yas/move-to-field snippet first-field)))
3403 (message "[yas] snippet expanded.")
3406 (defun yas/take-care-of-redo (beg end snippet)
3407 "Commits SNIPPET, which in turn pushes an undo action for
3410 Meant to exit in the `buffer-undo-list'."
3411 ;; slightly optimize: this action is only needed for snippets with
3412 ;; at least one field
3413 (when (yas/snippet-fields snippet)
3414 (yas/commit-snippet snippet)))
3416 (defun yas/snippet-revive (beg end snippet)
3417 "Revives the SNIPPET and creates a control overlay from BEG to
3420 BEG and END are, we hope, the original snippets boudaries. All
3421 the markers/points exiting existing inside SNIPPET should point
3422 to their correct locations *at the time the snippet is revived*.
3424 After revival, push the `yas/take-care-of-redo' in the
3426 ;; Reconvert all the points to markers
3428 (yas/points-to-markers snippet)
3429 ;; When at least one editable field existed in the zombie snippet,
3430 ;; try to revive the whole thing...
3432 (let ((target-field (or (yas/snippet-active-field snippet)
3433 (car (yas/snippet-fields snippet)))))
3435 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3436 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3438 (yas/move-to-field snippet target-field)
3440 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3441 buffer-undo-list))))
3443 (defun yas/snippet-create (begin end)
3444 "Creates a snippet from an template inserted between BEGIN and END.
3446 Returns the newly created snippet."
3447 (let ((snippet (yas/make-snippet)))
3449 (yas/snippet-parse-create snippet)
3451 ;; Sort and link each field
3452 (yas/snippet-sort-fields snippet)
3454 ;; Create keymap overlay for snippet
3455 (setf (yas/snippet-control-overlay snippet)
3456 (yas/make-control-overlay snippet (point-min) (point-max)))
3459 (goto-char (point-max))
3464 ;;; Apropos adjacencies and "fom's":
3466 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3467 ;; recently expanded snippet, we might actually have many fields,
3468 ;; mirrors (and the snippet exit) in the very same position in the
3469 ;; buffer. Therefore we need to single-link the
3470 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3471 ;; their original positions in the buffer.
3473 ;; Then we have operation `yas/advance-end-maybe' and
3474 ;; `yas/advance-start-maybe', which conditionally push the starts and
3475 ;; ends of these foms down the chain.
3477 ;; This allows for like the printf with the magic ",":
3479 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3480 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3482 (defun yas/fom-start (fom)
3483 (cond ((yas/field-p fom)
3484 (yas/field-start fom))
3486 (yas/mirror-start fom))
3488 (yas/exit-marker fom))))
3490 (defun yas/fom-end (fom)
3491 (cond ((yas/field-p fom)
3492 (yas/field-end fom))
3494 (yas/mirror-end fom))
3496 (yas/exit-marker fom))))
3498 (defun yas/fom-next (fom)
3499 (cond ((yas/field-p fom)
3500 (yas/field-next fom))
3502 (yas/mirror-next fom))
3504 (yas/exit-next fom))))
3506 (defun yas/fom-parent-field (fom)
3507 (cond ((yas/field-p fom)
3508 (yas/field-parent-field fom))
3510 (yas/mirror-parent-field fom))
3514 (defun yas/calculate-adjacencies (snippet)
3515 "Calculate adjacencies for fields or mirrors of SNIPPET.
3517 This is according to their relative positions in the buffer, and
3518 has to be called before the $-constructs are deleted."
3519 (flet ((yas/fom-set-next-fom (fom nextfom)
3520 (cond ((yas/field-p fom)
3521 (setf (yas/field-next fom) nextfom))
3523 (setf (yas/mirror-next fom) nextfom))
3525 (setf (yas/exit-next fom) nextfom))))
3526 (yas/compare-fom-begs (fom1 fom2)
3527 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3529 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3530 (yas/link-foms (fom1 fom2)
3531 (yas/fom-set-next-fom fom1 fom2)))
3532 ;; make some yas/field, yas/mirror and yas/exit soup
3534 (when (yas/snippet-exit snippet)
3535 (push (yas/snippet-exit snippet) soup))
3536 (dolist (field (yas/snippet-fields snippet))
3538 (dolist (mirror (yas/field-mirrors field))
3539 (push mirror soup)))
3542 #'yas/compare-fom-begs))
3544 (reduce #'yas/link-foms soup)))))
3546 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3547 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3549 Use the tighest containing field if more than one field contains
3550 the mirror. Intended to be called *before* the dollar-regions are
3552 (let ((min (point-min))
3554 (dolist (field (yas/snippet-fields snippet))
3555 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3556 (<= (yas/mirror-end mirror) (yas/field-end field))
3557 (< min (yas/field-start field))
3558 (< (yas/field-end field) max))
3559 (setq min (yas/field-start field)
3560 max (yas/field-end field))
3561 (setf (yas/mirror-parent-field mirror) field)))))
3563 (defun yas/advance-end-maybe (fom newend)
3564 "Maybe advance FOM's end to NEWEND if it needs it.
3568 * call `yas/advance-start-maybe' on FOM's next fom.
3570 * in case FOM is field call `yas/advance-end-maybe' on its parent
3573 Also, if FOM is an exit-marker, always call
3574 `yas/advance-start-maybe' on its next fom. This is beacuse
3575 exit-marker have identical start and end markers.
3578 (cond ((and fom (< (yas/fom-end fom) newend))
3579 (set-marker (yas/fom-end fom) newend)
3580 (yas/advance-start-maybe (yas/fom-next fom) newend)
3581 (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
3583 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3585 (defun yas/advance-start-maybe (fom newstart)
3586 "Maybe advance FOM's start to NEWSTART if it needs it.
3588 If it does, also call `yas/advance-end-maybe' on FOM."
3589 (when (and fom (< (yas/fom-start fom) newstart))
3590 (set-marker (yas/fom-start fom) newstart)
3591 (yas/advance-end-maybe fom newstart)))
3593 (defun yas/advance-end-of-parents-maybe (field newend)
3594 "Like `yas/advance-end-maybe' but for parent fields.
3596 Only works for fields and doesn't care about the start of the
3597 next FOM. Works its way up recursively for parents of parents."
3599 (< (yas/field-end field) newend))
3600 (set-marker (yas/field-end field) newend)
3601 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3603 (defvar yas/dollar-regions nil
3604 "When expanding the snippet the \"parse-create\" functions add
3605 cons cells to this var")
3607 (defun yas/snippet-parse-create (snippet)
3608 "Parse a recently inserted snippet template, creating all
3609 necessary fields, mirrors and exit points.
3611 Meant to be called in a narrowed buffer, does various passes"
3612 (let ((parse-start (point)))
3613 ;; Reset the yas/dollar-regions
3615 (setq yas/dollar-regions nil)
3616 ;; protect escaped quote, backquotes and backslashes
3618 (yas/protect-escapes nil `(?\\ ?` ?'))
3619 ;; replace all backquoted expressions
3621 (goto-char parse-start)
3622 (yas/replace-backquotes)
3623 ;; protect escapes again since previous steps might have generated
3624 ;; more characters needing escaping
3626 (goto-char parse-start)
3627 (yas/protect-escapes)
3628 ;; parse fields with {}
3630 (goto-char parse-start)
3631 (yas/field-parse-create snippet)
3632 ;; parse simple mirrors and fields
3634 (goto-char parse-start)
3635 (yas/simple-mirror-parse-create snippet)
3636 ;; parse mirror transforms
3638 (goto-char parse-start)
3639 (yas/transform-mirror-parse-create snippet)
3640 ;; calculate adjacencies of fields and mirrors
3642 (yas/calculate-adjacencies snippet)
3643 ;; Delete $-constructs
3645 (yas/delete-regions yas/dollar-regions)
3648 (goto-char parse-start)
3649 (yas/restore-escapes)
3650 ;; update mirrors for the first time
3652 (yas/update-mirrors snippet)
3653 ;; indent the best we can
3655 (goto-char parse-start)
3656 (yas/indent snippet)))
3658 (defun yas/indent-according-to-mode (snippet-markers)
3659 "Indent current line according to mode, preserving
3661 ;;; Apropos indenting problems....
3663 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3664 ;; is available. Some implementations of these functions delete text
3665 ;; before they insert. If there happens to be a marker just after
3666 ;; the text being deleted, the insertion actually happens after the
3667 ;; marker, which misplaces it.
3669 ;; This would also happen if we had used overlays with the
3670 ;; `front-advance' property set to nil.
3672 ;; This is why I have these `trouble-markers', they are the ones at
3673 ;; they are the ones at the first non-whitespace char at the line
3674 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3675 ;; we should be at the correct to restore them to. All other
3676 ;; non-trouble-markers have been *pushed* and don't need special
3679 (goto-char (yas/real-line-beginning))
3680 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3686 (indent-according-to-mode)
3687 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3689 (mapc #'(lambda (marker)
3690 (set-marker marker (point)))
3693 (defvar yas/indent-original-column nil)
3694 (defun yas/indent (snippet)
3695 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3696 ;; Look for those $>
3698 (while (re-search-forward "$>" nil t)
3699 (delete-region (match-beginning 0) (match-end 0))
3700 (when (not (eq yas/indent-line 'auto))
3701 (yas/indent-according-to-mode snippet-markers))))
3702 ;; Now do stuff for 'fixed and 'auto
3704 (cond ((eq yas/indent-line 'fixed)
3705 (while (and (zerop (forward-line))
3706 (zerop (current-column)))
3707 (indent-to-column yas/indent-original-column)))
3708 ((eq yas/indent-line 'auto)
3709 (let ((end (set-marker (make-marker) (point-max)))
3710 (indent-first-line-p yas/also-auto-indent-first-line))
3711 (while (and (zerop (if indent-first-line-p
3714 (setq indent-first-line-p nil))
3718 (yas/indent-according-to-mode snippet-markers))))
3722 (defun yas/collect-snippet-markers (snippet)
3723 "Make a list of all the markers used by SNIPPET."
3725 (dolist (field (yas/snippet-fields snippet))
3726 (push (yas/field-start field) markers)
3727 (push (yas/field-end field) markers)
3728 (dolist (mirror (yas/field-mirrors field))
3729 (push (yas/mirror-start mirror) markers)
3730 (push (yas/mirror-end mirror) markers)))
3731 (let ((snippet-exit (yas/snippet-exit snippet)))
3732 (when (and snippet-exit
3733 (marker-buffer (yas/exit-marker snippet-exit)))
3734 (push (yas/exit-marker snippet-exit) markers)))
3737 (defun yas/real-line-beginning ()
3738 (let ((c (char-after (line-beginning-position)))
3739 (n (line-beginning-position)))
3740 (while (or (eql c ?\ )
3743 (setq c (char-after n)))
3746 (defun yas/escape-string (escaped)
3747 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3749 (defun yas/protect-escapes (&optional text escaped)
3750 "Protect all escaped characters with their numeric ASCII value.
3752 With optional string TEXT do it in string instead of buffer."
3753 (let ((changed-text text)
3754 (text-provided-p text))
3755 (mapc #'(lambda (escaped)
3757 (yas/replace-all (concat "\\" (char-to-string escaped))
3758 (yas/escape-string escaped)
3759 (when text-provided-p changed-text))))
3760 (or escaped yas/escaped-characters))
3763 (defun yas/restore-escapes (&optional text escaped)
3764 "Restore all escaped characters from their numeric ASCII value.
3766 With optional string TEXT do it in string instead of the buffer."
3767 (let ((changed-text text)
3768 (text-provided-p text))
3769 (mapc #'(lambda (escaped)
3771 (yas/replace-all (yas/escape-string escaped)
3772 (char-to-string escaped)
3773 (when text-provided-p changed-text))))
3774 (or escaped yas/escaped-characters))
3777 (defun yas/replace-backquotes ()
3778 "Replace all the \"`(lisp-expression)`\"-style expression
3779 with their evaluated value"
3780 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3781 (let ((current-string (match-string 1)) transformed)
3782 (delete-region (match-beginning 0) (match-end 0))
3783 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3784 (goto-char (match-beginning 0))
3785 (when transformed (insert transformed)))))
3787 (defun yas/scan-sexps (from count)
3789 (with-syntax-table (standard-syntax-table)
3790 (scan-sexps from count))
3794 (defun yas/make-marker (pos)
3795 "Create a marker at POS with `nil' `marker-insertion-type'"
3796 (let ((marker (set-marker (make-marker) pos)))
3797 (set-marker-insertion-type marker nil)
3800 (defun yas/field-parse-create (snippet &optional parent-field)
3801 "Parse most field expressions, except for the simple one \"$n\".
3803 The following count as a field:
3805 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3807 * \"${n: text$(expression)}, the same with a lisp expression;
3808 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3810 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3812 When multiple expressions are found, only the last one counts."
3815 (while (re-search-forward yas/field-regexp nil t)
3816 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3817 (number (and (match-string-no-properties 1)
3818 (string-to-number (match-string-no-properties 1))))
3819 (brand-new-field (and real-match-end-0
3820 ;; break if on "$(" immediately
3821 ;; after the ":", this will be
3822 ;; caught as a mirror with
3824 (not (save-match-data
3825 (eq (string-match "$[ \t\n]*("
3826 (match-string-no-properties 2)) 0)))
3827 ;; allow ${0: some exit text}
3828 ;; (not (and number (zerop number)))
3829 (yas/make-field number
3830 (yas/make-marker (match-beginning 2))
3831 (yas/make-marker (1- real-match-end-0))
3833 (when brand-new-field
3834 (goto-char real-match-end-0)
3835 (push (cons (1- real-match-end-0) real-match-end-0)
3837 (push (cons (match-beginning 0) (match-beginning 2))
3839 (push brand-new-field (yas/snippet-fields snippet))
3842 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3843 (goto-char (point-min))
3844 (yas/field-parse-create snippet brand-new-field)))))))
3845 ;; if we entered from a parent field, now search for the
3846 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3847 ;; primary field transformations
3851 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3852 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3853 ;; commit the primary field transformation if:
3855 ;; 1. we don't find it in yas/dollar-regions (a subnested
3856 ;; field) might have already caught it.
3858 ;; 2. we really make sure we have either two '$' or some
3859 ;; text and a '$' after the colon ':'. This is a FIXME: work
3860 ;; my regular expressions and end these ugly hacks.
3862 (when (and real-match-end-1
3863 (not (member (cons (match-beginning 0)
3865 yas/dollar-regions))
3867 (char-before (1- (match-beginning 1))))))
3868 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3870 (setf (yas/field-transform parent-field)
3871 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3872 (push (cons (match-beginning 0) real-match-end-1)
3873 yas/dollar-regions)))))))
3875 (defun yas/transform-mirror-parse-create (snippet)
3876 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3877 (while (re-search-forward yas/transform-mirror-regexp nil t)
3878 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3879 (number (string-to-number (match-string-no-properties 1)))
3881 (not (zerop number))
3882 (yas/snippet-find-field snippet number)))
3884 (and real-match-end-0
3886 (yas/make-mirror (yas/make-marker (match-beginning 0))
3887 (yas/make-marker (match-beginning 0))
3889 (yas/restore-escapes
3890 (buffer-substring-no-properties (match-beginning 2)
3891 (1- real-match-end-0))))))))
3892 (when brand-new-mirror
3893 (push brand-new-mirror
3894 (yas/field-mirrors field))
3895 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3896 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3898 (defun yas/simple-mirror-parse-create (snippet)
3899 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3900 (while (re-search-forward yas/simple-mirror-regexp nil t)
3901 (let ((number (string-to-number (match-string-no-properties 1))))
3902 (cond ((zerop number)
3904 (setf (yas/snippet-exit snippet)
3905 (yas/make-exit (yas/make-marker (match-end 0))))
3907 (goto-char (match-beginning 0))
3908 (when yas/wrap-around-region
3909 (cond (yas/selected-text
3910 (insert yas/selected-text))
3911 ((and (eq yas/wrap-around-region 'cua)
3914 (insert (prog1 (get-register ?0)
3915 (set-register ?0 nil))))))
3916 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
3917 yas/dollar-regions)))
3919 (let ((field (yas/snippet-find-field snippet number)))
3921 (let ((brand-new-mirror (yas/make-mirror
3922 (yas/make-marker (match-beginning 0))
3923 (yas/make-marker (match-beginning 0))
3925 (push brand-new-mirror
3926 (yas/field-mirrors field))
3927 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
3928 (push (yas/make-field number
3929 (yas/make-marker (match-beginning 0))
3930 (yas/make-marker (match-beginning 0))
3932 (yas/snippet-fields snippet))))
3933 (push (cons (match-beginning 0) (match-end 0))
3934 yas/dollar-regions))))))
3936 (defun yas/delete-regions (regions)
3937 "Sort disjuct REGIONS by start point, then delete from the back."
3938 (mapc #'(lambda (reg)
3939 (delete-region (car reg) (cdr reg)))
3942 (>= (car r1) (car r2))))))
3944 (defun yas/update-mirrors (snippet)
3945 "Updates all the mirrors of SNIPPET."
3947 (let* ((fields (copy-list (yas/snippet-fields snippet)))
3948 (field (car fields)))
3950 (dolist (mirror (yas/field-mirrors field))
3951 (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
3952 ;; updatte this mirror
3954 (yas/mirror-update-display mirror field)
3955 ;; for mirrors-in-fields: schedule a possible
3956 ;; parent field for reupdting later on
3958 (when mirror-parent-field
3959 (add-to-list 'fields mirror-parent-field 'append #'eq))
3960 ;; `yas/place-overlays' is needed if the active field and
3961 ;; protected overlays have been changed because of insertions
3962 ;; in `yas/mirror-update-display'
3964 (when (eq field (yas/snippet-active-field snippet))
3965 (yas/place-overlays snippet field))))
3966 (setq fields (cdr fields))
3967 (setq field (car fields))))))
3969 (defun yas/mirror-update-display (mirror field)
3970 "Update MIRROR according to FIELD (and mirror transform)."
3972 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
3973 (reflection (and (not (and mirror-parent-field
3974 (yas/field-modified-p mirror-parent-field)))
3975 (or (yas/apply-transform mirror field 'empty-on-nil)
3976 (yas/field-text-for-display field)))))
3977 (when (and reflection
3978 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
3979 (yas/mirror-end mirror)))))
3980 (goto-char (yas/mirror-start mirror))
3981 (yas/inhibit-overlay-hooks
3982 (insert reflection))
3983 (if (> (yas/mirror-end mirror) (point))
3984 (delete-region (point) (yas/mirror-end mirror))
3985 (set-marker (yas/mirror-end mirror) (point))
3986 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
3987 ;; super-special advance
3988 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
3990 (defun yas/field-update-display (field snippet)
3991 "Much like `yas/mirror-update-display', but for fields"
3992 (when (yas/field-transform field)
3993 (let ((transformed (and (not (eq (yas/field-number field) 0))
3994 (yas/apply-transform field field)))
3996 (when (and transformed
3997 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
3998 (yas/field-end field)))))
3999 (setf (yas/field-modified-p field) t)
4000 (goto-char (yas/field-start field))
4001 (yas/inhibit-overlay-hooks
4002 (insert transformed)
4003 (if (> (yas/field-end field) (point))
4004 (delete-region (point) (yas/field-end field))
4005 (set-marker (yas/field-end field) (point))
4006 (yas/advance-start-maybe (yas/field-next field) (point)))
4010 ;;; Post-command hooks:
4012 (defvar yas/post-command-runonce-actions nil
4013 "List of actions to run once in `post-command-hook'.
4015 Each element of this list looks like (FN . ARGS) where FN is
4016 called with ARGS as its arguments after the currently executing
4019 After all actions have been run, this list is emptied, and after
4020 that the rest of `yas/post-command-handler' runs.")
4022 (defun yas/post-command-handler ()
4023 "Handles various yasnippet conditions after each command."
4024 (when yas/post-command-runonce-actions
4026 (mapc #'(lambda (fn-and-args)
4027 (apply (car fn-and-args)
4029 yas/post-command-runonce-actions)
4030 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4031 (setq yas/post-command-runonce-actions nil))
4032 (cond (yas/protection-violation
4033 (goto-char yas/protection-violation)
4034 (setq yas/protection-violation nil))
4035 ((eq 'undo this-command)
4037 ;; After undo revival the correct field is sometimes not
4038 ;; restored correctly, this condition handles that
4040 (let* ((snippet (car (yas/snippets-at-point)))
4041 (target-field (and snippet
4042 (find-if-not #'(lambda (field)
4043 (yas/field-probably-deleted-p snippet field))
4045 (cons (yas/snippet-active-field snippet)
4046 (yas/snippet-fields snippet)))))))
4048 (yas/move-to-field snippet target-field))))
4049 ((not (yas/undo-in-progress))
4050 ;; When not in an undo, check if we must commit the snippet
4051 ;; (user exited it).
4052 (yas/check-commit-snippet))))
4056 (put 'yas/expand 'function-documentation
4057 '(yas/expand-from-trigger-key-doc))
4058 (defun yas/expand-from-trigger-key-doc ()
4059 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4060 (let ((fallback-description
4061 (cond ((eq yas/fallback-behavior 'call-other-command)
4062 (let* ((yas/minor-mode nil)
4063 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4065 (format " call command `%s'." (pp-to-string fallback)))
4067 ((eq yas/fallback-behavior 'return-nil)
4070 ", defer to `yas/fallback-behaviour' :-)"))))
4071 (concat "Expand a snippet before point. If no snippet
4072 expansion is possible,"
4073 fallback-description
4074 "\n\nOptional argument FIELD is for non-interactive use and is an
4075 object satisfying `yas/field-p' to restrict the expansion to.")))
4077 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4078 (defun yas/expand-from-keymap-doc ()
4079 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4080 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4081 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4082 (when (eq this-command 'describe-key)
4083 (let* ((vec (this-single-command-keys))
4084 (templates (mapcan #'(lambda (table)
4085 (yas/fetch table vec))
4086 (yas/get-snippet-tables)))
4087 (yas/direct-keymaps nil)
4088 (fallback (key-binding vec)))
4089 (concat "In this case, "
4091 (concat "these snippets are bound to this key:\n"
4092 (yas/template-pretty-list templates)
4093 "\n\nIf none of these expands, "))
4095 (format "fallback `%s' will be called." (pp-to-string fallback)))
4096 "no fallback keybinding is called."))))))
4098 (defun yas/template-pretty-list (templates)
4100 (yas/buffer-local-condition 'always))
4101 (dolist (plate templates)
4102 (setq acc (concat acc "\n*) "
4103 (propertize (concat "\\\\snippet `" (car plate) "'")
4104 'yasnippet (cdr plate)))))
4107 (define-button-type 'help-snippet-def
4108 :supertype 'help-xref
4109 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4110 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4112 (defun yas/snippet-description-finish-runonce ()
4113 "Final adjustments for the help buffer when snippets are concerned."
4114 (yas/create-snippet-xrefs)
4115 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4117 (defun yas/create-snippet-xrefs ()
4119 (goto-char (point-min))
4120 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4121 (let ((template (get-text-property (match-beginning 1)
4124 (help-xref-button 1 'help-snippet-def template)
4125 (kill-region (match-end 1) (match-end 0))
4126 (kill-region (match-beginning 0) (match-beginning 1)))))))
4128 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4129 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4131 Remaining args as in `yas/expand-snippet'."
4132 (let* ((table (gethash mode-symbol yas/tables))
4133 (yas/current-template (and table
4134 (gethash uuid (yas/table-uuidhash table)))))
4135 (when yas/current-template
4136 (yas/expand-snippet (yas/template-content yas/current-template)))))
4141 ;; `locate-dominating-file'
4142 ;; `region-active-p'
4144 ;; added for compatibility in emacs < 23
4145 (unless (>= emacs-major-version 23)
4146 (unless (fboundp 'region-active-p)
4147 (defun region-active-p () (and transient-mark-mode mark-active)))
4149 (unless (fboundp 'locate-dominating-file)
4150 (defvar locate-dominating-stop-dir-regexp
4151 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4152 "Regexp of directory names which stop the search in `locate-dominating-file'.
4153 Any directory whose name matches this regexp will be treated like
4154 a kind of root directory by `locate-dominating-file' which will stop its search
4155 when it bumps into it.
4156 The default regexp prevents fruitless and time-consuming attempts to find
4157 special files in directories in which filenames are interpreted as hostnames,
4158 or mount points potentially requiring authentication as a different user.")
4160 (defun locate-dominating-file (file name)
4161 "Look up the directory hierarchy from FILE for a file named NAME.
4162 Stop at the first parent directory containing a file NAME,
4163 and return the directory. Return nil if not found."
4164 ;; We used to use the above locate-dominating-files code, but the
4165 ;; directory-files call is very costly, so we're much better off doing
4166 ;; multiple calls using the code in here.
4168 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4169 ;; `name' in /home or in /.
4170 (setq file (abbreviate-file-name file))
4173 ;; `user' is not initialized outside the loop because
4174 ;; `file' may not exist, so we may have to walk up part of the
4175 ;; hierarchy before we find the "initial UUID".
4178 (while (not (or root
4180 ;; FIXME: Disabled this heuristic because it is sometimes
4182 ;; As a heuristic, we stop looking up the hierarchy of
4183 ;; directories as soon as we find a directory belonging
4184 ;; to another user. This should save us from looking in
4185 ;; things like /net and /afs. This assumes that all the
4186 ;; files inside a project belong to the same user.
4187 ;; (let ((prev-user user))
4188 ;; (setq user (nth 2 (file-attributes file)))
4189 ;; (and prev-user (not (equal user prev-user))))
4190 (string-match locate-dominating-stop-dir-regexp file)))
4191 (setq try (file-exists-p (expand-file-name name file)))
4192 (cond (try (setq root file))
4193 ((equal file (setq prev-file file
4194 file (file-name-directory
4195 (directory-file-name file))))
4199 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4200 ;; (when it execute forward-char) and interrupt the after change
4201 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4202 ;; invoked. Here's a way to reproduce it:
4204 ;; # open a *new* Emacs.
4205 ;; # load yasnippet.
4206 ;; # open a *new* .cpp file.
4207 ;; # input "inc" and press TAB to expand the snippet.
4208 ;; # select the `#include <...>` snippet.
4209 ;; # type inside `<>`
4211 (defadvice c-neutralize-syntax-in-CPP
4212 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4213 "Adviced `c-neutralize-syntax-in-CPP' to properly
4214 handle the end-of-buffer error fired in it by calling
4215 `forward-char' at the end of buffer."
4218 (error (message (error-message-string err)))))
4220 ;; disable c-electric-* serial command in YAS fields
4221 (add-hook 'c-mode-common-hook
4223 (dolist (k '(":" ">" ";" "<" "{" "}"))
4224 (define-key (symbol-value (make-local-variable 'yas/keymap))
4225 k 'self-insert-command))))
4227 (provide 'yasnippet)
4229 ;;; yasnippet.el ends here