1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
3 ;; Copyright 2008 pluskid
5 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
7 ;; Package-version: 0.6.1b
8 ;; X-URL: http://code.google.com/p/yasnippet/
9 ;; Keywords: snippet, textmate
10 ;; URL: http://code.google.com/p/yasnippet/
11 ;; EmacsWiki: YaSnippetMode
13 ;; This file is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; This file is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Basic steps to setup:
32 ;; 1. In your .emacs file:
33 ;; (add-to-list 'load-path "/dir/to/yasnippet.el")
34 ;; (require 'yasnippet)
35 ;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets
36 ;; 3. In your .emacs file
37 ;; (setq yas/root-directory "~/.emacs/snippets")
38 ;; (yas/load-directory yas/root-directory)
39 ;; 4. To enable the YASnippet menu and tab-trigger expansion
41 ;; 5. To globally enable the minor mode in *all* buffers
42 ;; M-x yas/global-mode
44 ;; Steps 4. and 5. are optional, you don't have to use the minor
45 ;; mode to use YASnippet.
47 ;; Interesting variables are:
49 ;; `yas/root-directory'
51 ;; The directory where user-created snippets are to be
52 ;; stored. Can also be a list of directories that
53 ;; `yas/reload-all' will use for bulk-reloading snippets. In
54 ;; that case the first directory the default for storing new
59 ;; A local variable that you can set in a hook to override
60 ;; snippet-lookup based on major mode. It is a a symbol (or
61 ;; list of symbols) that correspond to subdirectories of
62 ;; `yas/root-directory' and is used for deciding which
63 ;; snippets to consider for the active buffer.
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/root-directory', 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/root-directory', 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 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
117 ;; can optionally use it the preferred "prompting method", puting in
118 ;; your .emacs file, for example:
120 ;; (require 'dropdown-list)
121 ;; (setq 'yas/prompt-functions '(yas/dropdown-prompt
123 ;; yas/completing-prompt))
125 ;; Also check out the customization group
127 ;; M-x customize-group RET yasnippet RET
129 ;; For more information and detailed usage, refer to the project page:
130 ;; http://code.google.com/p/yasnippet/
137 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
138 ;; User customizable variables
141 (defgroup yasnippet nil
142 "Yet Another Snippet extension"
145 (defcustom yas/root-directory nil
146 "Root directory that stores the snippets for each major mode.
148 Can also be a list of strings, for multiple root directories. If
149 you make this a list, the first element is always the
150 user-created snippets directory. Other directories are used for
151 bulk reloading of all snippets using `yas/reload-all'"
156 (defcustom yas/prompt-functions '(yas/x-prompt
158 yas/completing-prompt
161 "Functions to prompt for keys, templates, etc interactively."
165 (defcustom yas/indent-line 'auto
166 "Controls indenting applied to a recent snippet expansion.
168 The following values are possible:
170 `fixed' Indent the snippet to the current column;
172 `auto' Indent each line of the snippet with `indent-according-to-mode'
174 Every other value means don't apply any snippet-side indendation
175 after expansion (the manual per-line \"$>\" indentation still
177 :type '(choice (const :tag "Nothing" nothing)
178 (const :tag "Fixed" fixed)
179 (const :tag "Auto" auto))
182 (defcustom yas/also-auto-indent-first-line nil
183 "Non-nil means also auto indent first line according to mode.
185 Naturally this is only valid when `yas/indent-line' is `auto'"
189 (defcustom yas/snippet-revival t
190 "Non-nil means re-activate snippet fields after undo/redo."
194 (defcustom yas/trigger-key "TAB"
195 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
197 Value is a string that is converted to the internal Emacs key
198 representation using `read-kbd-macro'."
202 (defcustom yas/next-field-key "TAB"
203 "The key to navigate to next field when a snippet is active.
205 Value is a string that is converted to the internal Emacs key
206 representation using `read-kbd-macro'."
210 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
211 "The key to navigate to previous field when a snippet is active.
213 Can also be a list of keys.
215 Value is a string that is converted to the internal Emacs key
216 representation using `read-kbd-macro'."
220 (defcustom yas/skip-and-clear-key "C-d"
221 "The key to clear the currently active field.
223 Value is a string that is converted to the internal Emacs key
224 representation using `read-kbd-macro'."
228 (defcustom yas/triggers-in-field nil
229 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
231 Otherwise, `yas/next-field-key' just tries to move on to the next
236 (defcustom yas/fallback-behavior 'call-other-command
237 "How to act when `yas/trigger-key' does *not* expand a snippet.
239 The fall back behavior of YASnippet when it can't find a snippet
242 `call-other-command' means try to temporarily disable YASnippet
243 and call the next command bound to `yas/trigger-key'.
245 `return-nil' means return do nothing.
247 An entry (apply COMMAND . ARGS) means interactively call COMMAND,
248 if ARGS is non-nil, call COMMAND non-interactively with ARGS as
250 :type '(choice (const :tag "Call previous command" 'call-other-command)
251 (const :tag "Do nothing" 'return-nil))
254 (defcustom yas/choose-keys-first t
255 "If non-nil, prompts for key first, then for template if more than one.
257 Otherwise prompts for all possible templates
259 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
263 (defcustom yas/choose-tables-first nil
264 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
266 Otherwise, user chooses between the merging together of all
269 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
273 (defcustom yas/use-menu t
274 "Display a YASnippet menu in the menu bar.
276 When non-nil, snippet templates will be listed under the menu
277 \"Yasnippet\". If set to `abbreviate', only the current major-mode
278 menu and the modes set in `yas/mode-symbol' are listed."
279 :type '(choice (const :tag "Full" t)
280 (const :tag "Abbreviate" abbreviate))
283 (defcustom yas/trigger-symbol " =>"
284 "The text that will be used in menu to represent the trigger."
288 (defcustom yas/wrap-around-region nil
289 "If non-nil, snippet expansion wraps around selected region.
291 The wrapping occurs just before the snippet's exit marker. This
292 can be overriden on a per-snippet basis."
296 (defcustom yas/good-grace t
297 "If non-nil, don't raise errors in inline elisp evaluation.
299 An error string \"[yas] error\" is returned instead."
303 (defface yas/field-highlight-face
304 '((((class color) (background light)) (:background "DarkSeaGreen1"))
305 (t (:background "DimGrey")))
306 "The face used to highlight the currently active field of a snippet"
309 (defface yas/field-debug-face
311 "The face used for debugging some overlays normally hidden"
314 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
315 ;; User semi-customizable variables
318 (defvar yas/keymap (make-sparse-keymap)
319 "The keymap active while a snippet expansion is in progress.")
321 (defun yas/define-some-keys (keys keymap definition)
322 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
323 (let ((keys (or (and (listp keys) keys)
326 (define-key keymap (read-kbd-macro key) definition))))
328 (yas/define-some-keys yas/next-field-key yas/keymap 'yas/next-field-or-maybe-expand)
329 (yas/define-some-keys yas/prev-field-key yas/keymap 'yas/prev-field)
330 (yas/define-some-keys yas/skip-and-clear-key yas/keymap 'yas/skip-and-clear-or-delete-char)
332 (defvar yas/key-syntaxes (list "w" "w_" "w_." "^ ")
333 "A list of syntax of a key. This list is tried in the order
334 to try to find a key. For example, if the list is '(\"w\" \"w_\").
335 And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":
339 will first try \"bar\", if not found, then \"foo-bar\" is tried.")
341 (defvar yas/after-exit-snippet-hook
343 "Hooks to run after a snippet exited.
345 The hooks will be run in an environment where some variables bound to
348 `yas/snippet-beg' : The beginning of the region of the snippet.
350 `yas/snippet-end' : Similar to beg.
352 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
354 (defvar yas/before-expand-snippet-hook
356 "Hooks to run just before expanding a snippet.")
358 (defvar yas/buffer-local-condition
359 '(if (and (not (bobp))
360 (or (equal 'font-lock-comment-face
361 (get-char-property (1- (point))
363 (equal 'font-lock-string-face
364 (get-char-property (1- (point))
366 '(require-snippet-condition . force-in-comment)
368 "Condition to yasnippet local to each buffer.
370 The default value helps filtering out potential snippet
371 expansions inside comments and string literals, unless the
372 snippet itself contains a condition that returns the symbol
375 * If yas/buffer-local-condition evaluate to nil, snippet
378 * If it evaluate to the a cons cell where the car is the
379 symbol `require-snippet-condition' and the cdr is a
380 symbol (let's call it \"requirement\"):
381 * If the snippet has no condition, then it won't be
383 * If the snippet has a condition but it evaluates to nil or
384 error occured during evaluation, it won't be expanded.
385 * If the snippet has a condition that evaluate to
386 non-nil (let's call it \"result\"):
387 * If \"requirement\" is t, the snippet is ready to be
389 * If \"requirement\" is eq to \"result\", the snippet is ready
391 * Otherwise the snippet won't be expanded.
393 * If it evaluates to `always', snippet is unconditionally
396 * If it evaluates to other non-nil value:
397 * If the snippet has no condition, or has a condition that
398 evaluate to non-nil, it is ready to be expanded.
399 * Otherwise, it won't be expanded.
403 (add-hook 'python-mode-hook
405 (setq yas/buffer-local-condition
406 '(if (python-in-string/comment)
407 '(require-snippet-condition . force-in-comment)
409 (make-variable-buffer-local 'yas/buffer-local-condition)
411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
412 ;; Internal variables
415 (defvar yas/version "0.6.0b")
417 (defvar yas/snippet-tables (make-hash-table)
418 "A hash table of snippet tables corresponding to each major mode.")
420 (defvar yas/menu-table (make-hash-table)
421 "A hash table of menus of corresponding major mode.")
423 (defvar yas/known-modes
424 '(ruby-mode rst-mode markdown-mode)
425 "A list of mode which is well known but not part of emacs.")
427 (defvar yas/escaped-characters
429 "List of characters which *might* need to be escaped.")
431 (defconst yas/field-regexp
432 "${\\([0-9]+:\\)?\\([^}]*\\)}"
433 "A regexp to *almost* recognize a field.")
435 (defconst yas/multi-dollar-lisp-expression-regexp
436 "$+[ \t\n]*\\(([^)]*)\\)"
437 "A regexp to *almost* recognize a \"$(...)\" expression.")
439 (defconst yas/backquote-lisp-expression-regexp
441 "A regexp to recognize a \"`lisp-expression`\" expression." )
443 (defconst yas/transform-mirror-regexp
444 "${\\(?:\\([0-9]+\\):\\)?$\\([^}]*\\)"
445 "A regexp to *almost* recognize a mirror with a transform.")
447 (defconst yas/simple-mirror-regexp
449 "A regexp to recognize a simple mirror.")
451 (defvar yas/snippet-id-seed 0
452 "Contains the next id for a snippet.")
454 (defun yas/snippet-next-id ()
455 (let ((id yas/snippet-id-seed))
456 (incf yas/snippet-id-seed)
459 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
462 ;; TODO: XXX: This is somehow needed in Carbon Emacs for MacOSX
463 (defvar last-buffer-undo-list nil)
465 (defvar yas/minor-mode-map (make-sparse-keymap)
466 "The keymap used when function `yas/minor-mode' is active.")
468 (defvar yas/minor-mode-menu (make-sparse-keymap)
469 "Holds the YASnippet menu. For use with `easy-menu-define'.")
471 (defun yas/init-keymap-and-menu ()
472 (easy-menu-define yas/minor-mode-menu
474 "Menu used when YAS/minor-mode is active."
476 (mapcar #'(lambda (ent)
478 (define-key yas/minor-mode-map (third ent) (second ent)))
479 (vector (first ent) (second ent) t))
481 (list "Expand trigger" 'yas/expand (when yas/trigger-key (read-kbd-macro yas/trigger-key)))
482 (list "Insert at point..." 'yas/insert-snippet "\C-c&\C-s")
483 (list "Visit snippet file..." 'yas/visit-snippet-file "\C-c&\C-v")
484 (list "Find snippets..." 'yas/find-snippets "\C-c&\C-f")
485 (list "About" 'yas/about)
486 (list "Reload-all-snippets" 'yas/reload-all)
487 (list "Load snippets..." 'yas/load-directory))))))
489 (define-minor-mode yas/minor-mode
490 "Toggle YASnippet mode.
492 When YASnippet mode is enabled, the `tas/trigger-key' key expands
493 snippets of code depending on the mode.
495 With no argument, this command toggles the mode.
496 positive prefix argument turns on the mode.
497 Negative prefix argument turns off the mode.
499 You can customize the key through `yas/trigger-key'.
502 \\{yas/minor-mode-map}"
504 ;; The indicator for the mode line.
508 ;; when turning on theminor mode, re-read the `yas/trigger-key'
509 ;; if a `yas/minor-mode-map' is already built. Else, call
510 ;; `yas/init-keymap-and-menu' to build it
511 (if (and (cdr yas/minor-mode-map)
513 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)
514 (yas/init-keymap-and-menu))))
516 (defun yas/minor-mode-on ()
517 "Turn on YASnippet minor mode."
521 (defun yas/minor-mode-off ()
522 "Turn off YASnippet minor mode."
526 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
529 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
532 (defvar yas/font-lock-keywords
533 (append '(("^#.*$" . font-lock-comment-face))
534 lisp-font-lock-keywords
535 lisp-font-lock-keywords-1
536 lisp-font-lock-keywords-2
538 (0 font-lock-keyword-face)
539 (1 font-lock-string-face t))
541 (0 font-lock-keyword-face)
542 (1 font-lock-warning-face t))
543 ("${" font-lock-keyword-face)
544 ("$[0-9]+?" font-lock-preprocessor-face)
545 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
547 (0 font-lock-keyword-face)))))
549 (defvar snippet-mode-map (make-sparse-keymap))
550 (define-key snippet-mode-map "\C-c\C-c" 'yas/load-snippet-buffer)
551 (define-key snippet-mode-map "\C-c\C-t" 'yas/tryout-snippet)
554 (define-derived-mode snippet-mode text-mode "YASnippet"
555 "A mode for editing yasnippets"
556 (set-syntax-table (standard-syntax-table))
557 (setq font-lock-defaults '(yas/font-lock-keywords))
558 (set (make-local-variable 'require-final-newline) nil)
559 (use-local-map snippet-mode-map))
563 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; Internal structs for template management
567 (defstruct (yas/template (:constructor yas/make-template
568 (content name condition env file)))
569 "A template for a snippet."
576 (defstruct (yas/snippet-table (:constructor yas/make-snippet-table (name)))
577 "A table to store snippets for a perticular mode."
579 (hash (make-hash-table :test 'equal))
582 (defun yas/template-condition-predicate (condition)
589 (message (format "[yas]error in condition evaluation: %s"
590 (error-message-string err)))
594 (defun yas/filter-templates-by-condition (templates)
595 "Filter the templates using the applicable condition.
597 TEMPLATES is a list of cons (KEY . TEMPLATE) where KEY is a
598 string and TEMPLATE is a `yas/template' structure.
600 This function implements the rules described in
601 `yas/buffer-local-condition'. See that variables documentation."
602 (let ((requirement (yas/require-template-specific-condition-p)))
603 (if (eq requirement 'always)
605 (remove-if-not #'(lambda (pair)
606 (let* ((condition (yas/template-condition (cdr pair)))
607 (result (and condition
608 (yas/template-condition-predicate condition))))
609 (cond ((eq requirement t)
612 (eq requirement result)))))
615 (defun yas/snippet-table-fetch (table key)
616 "Fetch a snippet binding to KEY from TABLE."
618 (yas/filter-templates-by-condition (gethash key (yas/snippet-table-hash table)))))
620 (defun yas/snippet-table-get-all-parents (table)
621 (let ((parents (yas/snippet-table-parents table)))
624 (mapcan #'yas/snippet-table-get-all-parents parents)))))
626 (defun yas/snippet-table-templates (table)
629 (maphash #'(lambda (key templates)
630 (setq acc (append acc templates)))
631 (yas/snippet-table-hash table))
632 (yas/filter-templates-by-condition acc))))
634 (defun yas/snippet-table-all-keys (table)
637 (maphash #'(lambda (key templates)
638 (when (yas/filter-templates-by-condition templates)
640 (yas/snippet-table-hash table))
643 (defun yas/snippet-table-store (table full-key key template)
644 "Store a snippet template in the TABLE."
646 (yas/modify-alist (gethash key
647 (yas/snippet-table-hash table))
650 (yas/snippet-table-hash table)))
652 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
653 ;; Internal functions
656 (defun yas/real-mode? (mode)
657 "Try to find out if MODE is a real mode. The MODE bound to
658 a function (like `c-mode') is considered real mode. Other well
659 known mode like `ruby-mode' which is not part of Emacs might
660 not bound to a function until it is loaded. So yasnippet keeps
661 a list of modes like this to help the judgement."
663 (find mode yas/known-modes)))
665 (defun yas/eval-string (string)
666 ;; TODO: This is a possible optimization point, the expression could
667 ;; be stored in cons format instead of string,
668 "Evaluate STRING and convert the result to string."
669 (let ((retval (catch 'yas/exception
675 (let ((result (eval (read string))))
677 (format "%s" result))))))
678 (error (if yas/good-grace
680 (error (format "[yas] elisp error: %s"
681 (error-message-string err)))))))))
682 (when (and (consp retval)
683 (eq 'yas/exception (car retval)))
684 (error (cdr retval)))
687 (defvar yas/mode-symbol nil
688 "If non-nil, lookup snippets using this instead of `major-mode'.")
689 (make-variable-buffer-local 'yas/mode-symbol)
691 (defun yas/snippet-table-get-create (mode)
692 "Get the snippet table corresponding to MODE.
694 Optional DIRECTORY gets recorded as the default directory to
695 search for snippet files if the retrieved/created table didn't
696 already have such a property."
697 (let ((table (gethash mode
698 yas/snippet-tables)))
700 (setq table (yas/make-snippet-table (symbol-name mode)))
701 (puthash mode table yas/snippet-tables))
704 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
705 "Get snippet tables for current buffer.
707 Return tables in this order: optional MODE-SYMBOL, then
708 `yas/mode-symbol', then `major-mode' then, unless
709 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
710 MODE-SYMBOL or `major-mode'."
712 (mapcar #'(lambda (mode)
713 (gethash mode yas/snippet-tables))
714 (append (list mode-symbol)
715 (if (listp yas/mode-symbol)
717 (list yas/mode-symbol))
719 (and (not dont-search-parents)
720 (get (or mode-symbol major-mode)
721 'derived-mode-parent))))))
723 (dolist (table (remove nil mode-tables))
724 (push table all-tables)
725 (nconc all-tables (yas/snippet-table-get-all-parents table)))
726 (remove-duplicates all-tables)))
728 (defun yas/menu-keymap-get-create (mode)
729 "Get the menu keymap correspondong to MODE."
730 (or (gethash mode yas/menu-table)
731 (puthash mode (make-sparse-keymap) yas/menu-table)))
733 (defun yas/current-key ()
734 "Get the key under current position. A key is used to find
735 the template of a snippet in the current snippet-table."
736 (let ((start (point))
738 (syntaxes yas/key-syntaxes)
739 syntax done templates)
740 (while (and (not done) syntaxes)
741 (setq syntax (car syntaxes))
742 (setq syntaxes (cdr syntaxes))
744 (skip-syntax-backward syntax)
745 (setq start (point)))
747 (mapcan #'(lambda (table)
748 (yas/snippet-table-fetch table (buffer-substring-no-properties start end)))
749 (yas/get-snippet-tables)))
757 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
758 ;;; Template-related and snippet loading functions
760 (defun yas/parse-template (&optional file)
761 "Parse the template in the current buffer.
763 Optional FILE is the absolute file name of the file being
766 Return a snippet-definition, i.e. a list
768 (KEY TEMPLATE NAME CONDITION GROUP ENV)
770 If the buffer contains a line of \"# --\" then the contents
771 above this line are ignored. Variables can be set above this
772 line through the syntax:
776 Here's a list of currently recognized variables:
785 #name: #include \"...\"
788 (goto-char (point-min))
789 (let* ((name (and file (file-name-nondirectory file)))
796 (if (re-search-forward "^# --\n" nil t)
797 (progn (setq template
798 (buffer-substring-no-properties (point)
801 (goto-char (point-min))
802 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
803 (when (string= "name" (match-string-no-properties 1))
804 (setq name (match-string-no-properties 2)))
805 (when (string= "condition" (match-string-no-properties 1))
806 (setq condition (read (match-string-no-properties 2))))
807 (when (string= "group" (match-string-no-properties 1))
808 (setq group (match-string-no-properties 2)))
809 (when (string= "env" (match-string-no-properties 1))
810 (setq env (match-string-no-properties 2)))
811 (when (string= "key" (match-string-no-properties 1))
812 (setq key (match-string-no-properties 2)))))
814 (buffer-substring-no-properties (point-min) (point-max))))
815 (list key template name condition group env file)))
817 (defun yas/subdirs (directory &optional file?)
818 "Return subdirs or files of DIRECTORY according to FILE?."
819 (remove-if (lambda (file)
820 (or (string-match "^\\."
821 (file-name-nondirectory file))
823 (file-name-nondirectory file))
825 (file-directory-p file)
826 (not (file-directory-p file)))))
827 (directory-files directory t)))
829 (defun yas/make-menu-binding (template)
830 `(lambda () (interactive) (yas/expand-from-menu ,template)))
832 (defun yas/expand-from-menu (template)
833 (let ((where (if mark-active
834 (cons (region-beginning) (region-end))
835 (cons (point) (point)))))
836 (yas/expand-snippet (car where)
838 (yas/template-content template))))
840 (defun yas/modify-alist (alist key value)
841 "Modify ALIST to map KEY to VALUE. return the new alist."
842 (let ((pair (assoc key alist)))
844 (cons (cons key value)
849 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
850 ;; Popping up for keys and templates
852 (defun yas/prompt-for-template (templates &optional prompt)
853 "Interactively choose a template from the list TEMPLATES.
855 TEMPLATES is a list of `yas/template'."
858 (funcall fn (or prompt "Choose a snippet: ")
860 #'yas/template-name))
861 yas/prompt-functions)))
863 (defun yas/prompt-for-keys (keys &optional prompt)
864 "Interactively choose a template key from the list KEYS."
867 (funcall fn (or prompt "Choose a snippet key: ") keys))
868 yas/prompt-functions)))
870 (defun yas/prompt-for-table (tables &optional prompt)
873 (funcall fn (or prompt "Choose a snippet table: ")
875 #'yas/snippet-table-name))
876 yas/prompt-functions)))
878 (defun yas/x-prompt (prompt choices &optional display-fn)
879 (when (and window-system choices)
880 (let ((keymap (cons 'keymap
883 (mapcar (lambda (choice)
887 (funcall display-fn choice)
892 (car (x-popup-menu (if (fboundp 'posn-at-point)
893 (let ((x-y (posn-x-y (posn-at-point (point)))))
894 (list (list (+ (car x-y) 10)
900 (defun yas/ido-prompt (prompt choices &optional display-fn)
901 (when (and (featurep 'ido)
903 (let* ((formatted-choices (or (and display-fn
904 (mapcar display-fn choices))
906 (chosen (and formatted-choices
907 (ido-completing-read prompt
914 (nth (position chosen formatted-choices :test #'string=) choices)))))
916 (eval-when-compile (require 'dropdown-list nil t))
917 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
918 (when (featurep 'dropdown-list)
919 (let* ((formatted-choices (or (and display-fn
920 (mapcar display-fn choices))
922 (chosen (and formatted-choices
923 (nth (dropdown-list formatted-choices)
927 (defun yas/completing-prompt (prompt choices &optional display-fn)
928 (let* ((formatted-choices (or (and display-fn
929 (mapcar display-fn choices))
931 (chosen (and formatted-choices
932 (completing-read prompt
939 (nth (position chosen formatted-choices :test #'string=) choices))))
941 (defun yas/no-prompt (prompt choices &optional display-fn)
944 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
945 ;; Loading snippets from files
947 (defun yas/load-directory-1 (directory &optional parents no-hierarchy-parents)
948 "Recursively load snippet templates from DIRECTORY."
950 (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents (concat directory "/dummy")
952 no-hierarchy-parents))
953 (mode-sym (car major-mode-and-parents))
954 (parents (rest major-mode-and-parents))
957 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
958 (when (file-readable-p file)
959 (insert-file-contents file nil nil nil t)
960 (push (yas/parse-template file)
962 (yas/define-snippets mode-sym
965 (dolist (subdir (yas/subdirs directory))
966 (yas/load-directory-1 subdir (list mode-sym)))))
968 (defun yas/load-directory (directory)
969 "Load snippet definition from a directory hierarchy.
971 Below the top-level directory, each directory is a mode
972 name. And under each subdirectory, each file is a definition
973 of a snippet. The file name is the trigger key and the
974 content of the file is the template."
975 (interactive "DSelect the root directory: ")
976 (unless (file-directory-p directory)
977 (error "Error %s not a directory" directory))
978 (add-to-list 'yas/root-directory directory)
979 (dolist (dir (yas/subdirs directory))
980 (yas/load-directory-1 dir nil 'no-hierarchy-parents))
981 (when (interactive-p)
984 (defun yas/reload-all ()
985 "Reload all snippets and rebuild the YASnippet menu. "
988 (let ((restore-global-mode nil)
989 (restore-minor-mode nil))
990 (setq yas/snippet-tables (make-hash-table))
991 (setq yas/menu-table (make-hash-table))
992 (setf (cdr yas/minor-mode-menu) nil)
993 (setf (cdr yas/minor-mode-map) nil)
994 (when yas/global-mode
996 (setq restore-global-mode t))
1000 (setq restore-minor-mode t))
1002 (yas/init-keymap-and-menu)
1004 (if yas/root-directory
1005 (if (listp yas/root-directory)
1006 (dolist (directory yas/root-directory)
1007 (yas/load-directory directory))
1008 (yas/load-directory yas/root-directory))
1009 (call-interactively 'yas/load-directory))
1012 (when restore-minor-mode
1015 (when restore-global-mode
1016 (yas/global-mode 1))
1020 (defun yas/quote-string (string)
1021 "Escape and quote STRING.
1022 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1024 (replace-regexp-in-string "[\\\"]"
1029 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1030 ;;; Yasnippet Bundle
1032 (defun yas/initialize ()
1033 "For backward compatibility, enable `yas/minor-mode' globally"
1034 (yas/global-mode 1))
1036 (defun yas/compile-bundle
1037 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1038 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1039 SNIPPET-ROOTS is a list of root directories that contains the
1040 snippets definition. YASNIPPET is the yasnippet.el file
1041 path. YASNIPPET-BUNDLE is the output file of the compile
1042 result. CODE is the code you would like to used to initialize
1043 yasnippet. Last optional argument DROPDOWN is the filename of the
1044 dropdown-list.el library.
1046 Here's the default value for all the parameters:
1048 (yas/compile-bundle \"yasnippet.el\"
1049 \"./yasnippet-bundle.el\"
1051 \"(yas/initialize)\")
1056 (when (null yasnippet)
1057 (setq yasnippet "yasnippet.el"))
1058 (when (null yasnippet-bundle)
1059 (setq yasnippet-bundle "./yasnippet-bundle.el"))
1060 (when (null snippet-roots)
1061 (setq snippet-roots '("snippets")))
1062 (when (null dropdown)
1063 (setq dropdown "dropdown-list.el"))
1065 (setq code (concat "(yas/initialize-bundle)"
1066 "\n;;;###autoload" ; break through so that won't
1067 "(require 'yasnippet-bundle)"))) ; be treated as magic comment
1069 (let ((dirs (or (and (listp snippet-roots) snippet-roots)
1070 (list snippet-roots)))
1071 (bundle-buffer nil))
1073 (setq bundle-buffer (current-buffer))
1074 (insert ";;; yasnippet-bundle.el --- "
1075 "Yet another snippet extension (Auto compiled bundle)\n")
1076 (insert-file-contents yasnippet)
1077 (goto-char (point-max))
1080 (insert-file-contents dropdown))
1081 (goto-char (point-max))
1082 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1083 (insert ";;;; Auto-generated code ;;;;\n")
1084 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1085 (insert "(defun yas/initialize-bundle ()\n"
1086 " \"Initialize YASnippet and load snippets in the bundle.\""
1087 " (yas/global-mode 1)\n")
1088 (flet ((yas/define-snippets
1089 (mode snippets &optional parent directory)
1090 (with-current-buffer bundle-buffer
1091 (insert ";;; snippets for " (symbol-name mode) "\n")
1092 (insert "(yas/define-snippets '" (symbol-name mode) "\n")
1094 (dolist (snippet snippets)
1096 (yas/quote-string (car snippet))
1098 (yas/quote-string (nth 1 snippet))
1101 (yas/quote-string (nth 2 snippet))
1105 (format "'%s" (nth 3 snippet))
1109 (yas/quote-string (nth 4 snippet))
1114 (concat "'" (symbol-name parent))
1117 ;; (concat "\"" directory "\"")
1121 (dolist (subdir (yas/subdirs dir))
1122 (yas/load-directory-1 subdir nil))))
1124 (insert ")\n\n" code "\n")
1125 (insert "(provide '"
1126 (file-name-nondirectory
1127 (file-name-sans-extension
1131 (file-name-nondirectory yasnippet-bundle)
1133 (setq buffer-file-name yasnippet-bundle)
1136 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1137 ;;; Some user level functions
1142 (message (concat "yasnippet (version "
1144 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1146 (defun yas/define-snippets (mode snippets &optional parent-mode)
1147 "Define snippets for MODE. SNIPPETS is a list of
1148 snippet definitions, each taking the following form:
1150 (KEY TEMPLATE NAME CONDITION GROUP)
1152 NAME, CONDITION or GROUP may be omitted.
1154 Optional PARENT-MODE can be used to specify the parent modes of
1155 MODE. It can be a mode symbol of a list of mode symbols. It does
1156 not need to be a real mode.
1158 That is, when looking a snippet in MODE failed, it can refer to
1160 (let ((snippet-table (yas/snippet-table-get-create mode))
1161 (parent-tables (mapcar #'yas/snippet-table-get-create
1162 (if (listp parent-mode)
1164 (list parent-mode))))
1165 (keymap (if yas/use-menu
1166 (yas/menu-keymap-get-create mode)
1169 (setf (yas/snippet-table-parents snippet-table)
1172 (let ((parent-menu-syms-and-names
1173 (if (listp parent-mode)
1174 (mapcar #'(lambda (sym)
1175 (cons sym (concat "parent mode - " (symbol-name sym))))
1177 '((parent-mode . "parent mode")))))
1178 (mapc #'(lambda (sym-and-name)
1179 (define-key keymap (vector (intern (replace-regexp-in-string " " "_" (cdr sym-and-name))))
1180 (list 'menu-item (cdr sym-and-name)
1181 (yas/menu-keymap-get-create (car sym-and-name)))))
1182 (reverse parent-menu-syms-and-names)))))
1183 (when (and yas/use-menu
1184 (yas/real-mode? mode))
1185 (define-key yas/minor-mode-menu (vector mode)
1186 `(menu-item ,(symbol-name mode) ,keymap
1187 :visible (yas/show-menu-p ',mode))))
1188 (dolist (snippet snippets)
1189 (let* ((full-key (car snippet))
1190 (key (file-name-sans-extension full-key))
1191 (name (or (nth 2 snippet) (file-name-extension full-key)))
1192 (condition (nth 3 snippet))
1193 (group (nth 4 snippet))
1194 (template (yas/make-template (nth 1 snippet)
1199 (yas/snippet-table-store snippet-table
1204 (let ((group-keymap keymap))
1205 ;; delete this entry from another group if already exists
1206 ;; in some other group. An entry is considered as existing
1207 ;; in another group if its name string-matches.
1208 (yas/delete-from-keymap group-keymap name)
1210 ;; ... then add this entry to the correct group
1211 (when (and (not (null group))
1212 (not (string= "" group)))
1213 (dolist (subgroup (mapcar #'make-symbol
1214 (split-string group "\\.")))
1215 (let ((subgroup-keymap (lookup-key group-keymap
1216 (vector subgroup))))
1217 (when (null subgroup-keymap)
1218 (setq subgroup-keymap (make-sparse-keymap))
1219 (define-key group-keymap (vector subgroup)
1220 `(menu-item ,(symbol-name subgroup)
1222 (setq group-keymap subgroup-keymap))))
1223 (define-key group-keymap (vector (make-symbol full-key))
1224 `(menu-item ,(yas/template-name template)
1225 ,(yas/make-menu-binding template)
1226 :keys ,(concat key yas/trigger-symbol)))))))))
1228 (defun yas/show-menu-p (mode)
1230 (or (not (eq yas/use-menu 'abbreviate))
1231 (find mode (cons major-mode
1232 (if (listp yas/mode-symbol)
1234 (list yas/mode-symbol))))))
1236 (defun yas/delete-from-keymap (keymap name)
1237 "Recursively delete items name NAME from KEYMAP and its submenus.
1239 Skip any submenus named \"parent mode\""
1240 ;; First of all, recursively enter submenus, i.e. the tree is
1241 ;; searched depth first so that stale submenus can be found in the
1244 (mapc #'(lambda (item)
1245 (when (and (keymapp (fourth item))
1246 (stringp (third item))
1247 (not (string-match "parent mode" (third item))))
1248 (yas/delete-from-keymap (fourth item) name)))
1251 (when (keymapp keymap)
1252 (let ((pos-in-keymap))
1253 (while (setq pos-in-keymap (position-if #'(lambda (item)
1256 ;; the menu item we want to delete
1257 (and (eq 'menu-item (second item))
1259 (and (string= (third item) name)))
1261 (and (keymapp (fourth item))
1262 (not (and (stringp (third item))
1263 (string-match "parent mode" (third item))))
1264 (null (rest (fourth item)))))))
1266 (setf (nthcdr pos-in-keymap keymap)
1267 (nthcdr (+ 1 pos-in-keymap) keymap))))))
1269 (defun yas/define (mode key template &optional name condition group)
1270 "Define a snippet. Expanding KEY into TEMPLATE.
1272 NAME is a description to this template. Also update the menu if
1273 `yas/use-menu' is `t'. CONDITION is the condition attached to
1274 this snippet. If you attach a condition to a snippet, then it
1275 will only be expanded when the condition evaluated to non-nil."
1276 (yas/define-snippets mode
1277 (list (list key template name condition group))))
1279 (defun yas/hippie-try-expand (first-time?)
1280 "Integrate with hippie expand. Just put this function in
1281 `hippie-expand-try-functions-list'."
1282 (if (not first-time?)
1283 (let ((yas/fallback-behavior 'return-nil))
1288 (defun yas/require-template-specific-condition-p ()
1289 "Decides if this buffer requests/requires snippet-specific
1290 conditions to filter out potential expansions."
1291 (if (eq 'always yas/buffer-local-condition)
1293 (let ((local-condition (yas/template-condition-predicate
1294 yas/buffer-local-condition)))
1295 (when local-condition
1296 (if (eq local-condition t)
1298 (and (consp local-condition)
1299 (eq 'require-snippet-condition (car local-condition))
1300 (symbolp (cdr local-condition))
1301 (cdr local-condition)))))))
1303 (defun yas/expand ()
1304 "Expand a snippet before point.
1306 If no snippet expansion is possible, fall back to the behaviour
1307 defined in `yas/fallback-behavior'"
1311 (defun yas/expand-1 (&optional field)
1312 "Actually fo the work for `yas/expand'"
1313 (multiple-value-bind (templates start end) (if field
1315 (narrow-to-region (yas/field-start field) (yas/field-end field))
1319 (let ((template (or (and (rest templates) ;; more than one
1320 (yas/prompt-for-template (mapcar #'cdr templates)))
1323 (yas/expand-snippet start
1325 (yas/template-content template)
1326 (yas/template-env template))))
1327 (cond ((eq yas/fallback-behavior 'return-nil)
1330 ((eq yas/fallback-behavior 'call-other-command)
1331 (let* ((yas/minor-mode nil)
1332 (command (key-binding (read-kbd-macro yas/trigger-key))))
1333 (when (commandp command)
1334 (setq this-command command)
1335 (call-interactively command))))
1336 ((and (listp yas/fallback-behavior)
1337 (cdr yas/fallback-behavior)
1338 (eq 'apply (car yas/fallback-behavior)))
1339 (if (cddr yas/fallback-behavior)
1340 (apply (cadr yas/fallback-behavior)
1341 (cddr yas/fallback-behavior))
1342 (when (commandp (cadr yas/fallback-behavior))
1343 (setq this-command (cadr yas/fallback-behavior))
1344 (call-interactively (cadr yas/fallback-behavior)))))
1346 ;; also return nil if all the other fallbacks have failed
1349 (defun yas/all-templates (tables)
1350 "Return all snippet tables applicable for the current buffer.
1352 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
1353 `yas/buffer-local-condition'"
1354 (when yas/choose-tables-first
1355 (setq tables (list (yas/prompt-for-table tables))))
1357 (if yas/choose-keys-first
1358 (let ((key (yas/prompt-for-keys
1359 (mapcan #'yas/snippet-table-all-keys tables))))
1361 (mapcan #'(lambda (table)
1362 (yas/snippet-table-fetch table key))
1364 (mapcan #'yas/snippet-table-templates tables))))
1366 (defun yas/insert-snippet (&optional no-condition)
1367 "Choose a snippet to expand, pop-up a list of choices according
1368 to `yas/prompt-function'.
1370 With prefix argument NO-CONDITION, bypass filtering of snippets
1373 (let* ((yas/buffer-local-condition (or (and no-condition
1375 yas/buffer-local-condition))
1376 (templates (yas/all-templates (yas/get-snippet-tables)))
1377 (template (and templates
1378 (or (and (rest templates) ;; more than one template for same key
1379 (yas/prompt-for-template templates))
1381 (where (if mark-active
1382 (cons (region-beginning) (region-end))
1383 (cons (point) (point)))))
1385 (yas/expand-snippet (car where)
1387 (yas/template-content template)
1388 (yas/template-env template))
1389 (message "[yas] No snippets can be inserted here!"))))
1391 (defun yas/visit-snippet-file ()
1392 "Choose a snippet to edit, selection like `yas/insert-snippet'.
1394 Only success if selected snippet was loaded from a file. Put the
1395 visited file in `snippet-mode'."
1397 (let* ((yas/buffer-local-condition 'always)
1398 (templates (yas/all-templates (yas/get-snippet-tables)))
1399 (template (and templates
1400 (or (and (rest templates) ;; more than one template for same key
1401 (yas/prompt-for-template templates
1402 "Choose a snippet template to edit: "))
1406 (let ((file (yas/template-file template)))
1407 (cond ((and file (file-exists-p file))
1408 (find-file-other-window file)
1411 (message "Original file %s no longer exists!" file))
1413 (message "This snippet was not loaded from a file!")))))))
1415 (defun yas/guess-snippet-directory ()
1416 "Try to guess suitable directories based on `major-mode' and
1417 also the current active tables."
1418 (let ((main-dir (or (and (listp yas/root-directory)
1419 (first yas/root-directory))
1421 "~/.emacs.d/snippets"))
1424 ;; Lookup main mode and add that to the options
1426 (push (format "%s/%s" main-dir mode) options)
1427 ;; Next lookup the main active table
1429 (let ((active-tables (first (yas/get-snippet-tables)))
1430 (other-path-alternative main-dir))
1432 (setq active-tables (cons active-tables
1433 (yas/snippet-table-get-all-parents active-tables))))
1434 (dolist (table (reverse active-tables))
1435 (setq other-path-alternative
1436 (concat other-path-alternative "/" (yas/snippet-table-name table))))
1437 (push other-path-alternative options))
1438 ;; Finally add to the options the guessed parent of major-mode
1439 ;; (this is almost never works out)
1440 (when (get mode 'derived-mode-parent)
1441 (push (format "%s/%s" main-dir (get mode 'derived-mode-parent)) options))
1444 (defun yas/new-snippet (&optional same-window)
1445 "Create a new snippet in guessed current mode's directory."
1447 (yas/find-snippets same-window
1448 (read-from-minibuffer "Enter snippet name: ")))
1451 (defun yas/find-snippets (&optional same-window file-name)
1452 "Look for user snippets in guessed current mode's directory.
1454 Calls `find-file' interactively in the guessed directory.
1456 With prefix arg SAME-WINDOW opens the buffer in the same window.
1458 With optional FILE-NAME, finds the file directly, i.e. `find-file' is
1459 called non-interactively.
1461 Because snippets can be loaded from many different locations,
1462 this has to guess the correct directory using
1463 `yas/guess-directory', which returns a list of options. If any
1464 one of these exists, it is taken and `find-file' is called there,
1465 otherwise, proposes to create the first option returned by
1466 `yas/guess-directory'."
1468 (let* ((guessed-directories (yas/guess-snippet-directory))
1469 (target-directory (first (remove-if-not #'file-exists-p guessed-directories)))
1472 (unless target-directory
1473 (when (y-or-n-p (format "Guessed directory (%s) does not exist! Create? " (first guessed-directories)))
1474 (setq target-directory (first guessed-directories))
1475 (make-directory target-directory 'also-make-parents)))
1477 (when target-directory
1478 (let ((default-directory target-directory))
1479 (setq buffer (if file-name
1481 (find-file file-name)
1482 (find-file-other-window file-name))
1483 (call-interactively (if same-window
1485 'find-file-other-window))))
1489 (when (eq major-mode 'fundamental-mode)
1490 (snippet-mode))))))))
1492 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed no-hierarchy-parents)
1493 (let* ((file-dir (and file
1494 (directory-file-name (file-name-directory file))))
1495 (major-mode-name (and file-dir
1496 (file-name-nondirectory file-dir)))
1497 (parent-file-dir (and file-dir
1498 (directory-file-name (file-name-directory file-dir))))
1499 (parent-mode-name (and parent-file-dir
1500 (not no-hierarchy-parents)
1501 (file-name-nondirectory parent-file-dir)))
1502 (major-mode-sym (or (and major-mode-name
1503 (intern major-mode-name))
1504 (when prompt-if-failed
1505 (read-from-minibuffer "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
1506 (parent-mode-sym (and parent-mode-name
1507 (intern parent-mode-name)))
1508 (extra-parents-file-name (concat file-dir "/.yas-parents"))
1509 (more-parents (when (file-readable-p extra-parents-file-name)
1513 (insert-file extra-parents-file-name)
1514 (buffer-substring-no-properties (point-min)
1516 (when major-mode-sym
1517 (remove nil (append (list major-mode-sym parent-mode-sym)
1520 (defun yas/load-snippet-buffer (&optional kill)
1521 "Parse and load current buffer's snippet definition.
1523 With optional prefix argument KILL quit the window and buffer."
1525 (if buffer-file-name
1526 (let ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name)))
1527 (if major-mode-and-parent
1528 (let* ((parsed (yas/parse-template buffer-file-name))
1532 (yas/define-snippets (car major-mode-and-parent)
1534 (cdr major-mode-and-parent))
1535 (when (and (buffer-modified-p)
1536 (y-or-n-p "Save snippet? "))
1540 (message "[yas] Snippet \"%s\" loaded for %s." name (car major-mode-and-parent)))))
1541 (message "[yas] Cannot load snippet for unknown major mode")))
1542 (message "Save the buffer as a file first!")))
1544 (defun yas/tryout-snippet (&optional debug)
1545 "Test current buffers's snippet template in other buffer."
1547 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
1548 (parsed (and major-mode-and-parent
1549 (fboundp (car major-mode-and-parent))
1550 (yas/parse-template (symbol-name (car major-mode-and-parent)))))
1551 (template (and parsed
1552 (yas/make-template (second parsed) (third parsed) nil (sixth parsed) nil))))
1554 (let ((buffer-name (format "*YAS TEST: %s*" (yas/template-name template))))
1555 (set-buffer (switch-to-buffer buffer-name))
1557 (setq buffer-undo-list nil)
1558 (funcall (car major-mode-and-parent))
1559 (yas/expand-snippet (point-min) (point-max) (yas/template-content template) (yas/template-env template))
1561 (add-hook 'post-command-hook 'yas/debug-some-vars 't 'local))))
1563 (message "[yas] Cannot test snippet for unknown major mode")))))
1565 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1566 ;;; User convenience functions, for using in snippet definitions
1569 (defvar yas/modified-p nil
1570 "Non-nil if field has been modified by user or transformation.")
1572 (defvar yas/moving-away-p nil
1573 "Non-nil if user is about to exit field.")
1575 (defvar yas/text nil
1576 "Contains current field text.")
1578 (defun yas/substr (str pattern &optional subexp)
1579 "Search PATTERN in STR and return SUBEXPth match.
1581 If found, the content of subexp group SUBEXP (default 0) is
1582 returned, or else the original STR will be returned."
1583 (let ((grp (or subexp 0)))
1585 (if (string-match pattern str)
1586 (match-string-no-properties grp str)
1589 (defun yas/choose-value (possibilities)
1590 "Prompt for a string in the list POSSIBILITIES and return it."
1591 (unless (or yas/moving-away-p
1593 (some #'(lambda (fn)
1594 (funcall fn "Choose: " possibilities))
1595 yas/prompt-functions)))
1597 (defun yas/key-to-value (alist)
1598 "Prompt for a string in the list POSSIBILITIES and return it."
1599 (unless (or yas/moving-away-p
1601 (let ((key (read-key-sequence "")))
1603 (or (cdr (find key alist :key #'car :test #'string=))
1606 (defun yas/throw (text)
1607 "Throw a yas/exception with TEXT as the reason."
1608 (throw 'yas/exception (cons 'yas/exception text)))
1610 (defun yas/verify-value (possibilities)
1611 "Verify that the current field value is in POSSIBILITIES
1613 Otherwise throw exception."
1614 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
1615 (yas/throw (format "[yas] field only allows %s" possibilities))))
1617 (defun yas/field-value (number)
1618 (let* ((snippet (car (yas/snippets-at-point)))
1620 (yas/snippet-find-field snippet number))))
1622 (yas/field-text-for-display field))))
1624 (defun yas/oni (text oni-regexp)
1625 "Runs ruby to parse TEXT with Oniguruma regexp ONI-REGEXP."
1626 (shell-command-to-string (format "ruby -e 'print \"%s\".gsub(\"a\",\"b\")'" "aha")))
1629 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1630 ;;; Snippet expansion and field management
1632 (defvar yas/active-field-overlay nil
1633 "Overlays the currently active field.")
1635 (defvar yas/field-protection-overlays nil
1636 "Two overlays protect the current active field ")
1638 (defvar yas/deleted-text nil
1639 "The text deleted in the last snippet expansion.")
1641 (defvar yas/selected-text nil
1642 "The selected region deleted on the last snippet expansion.")
1644 (defvar yas/start-column nil
1645 "The column where the snippet expansion started.")
1647 (make-variable-buffer-local 'yas/active-field-overlay)
1648 (make-variable-buffer-local 'yas/field-protection-overlays)
1649 (make-variable-buffer-local 'yas/deleted-text)
1651 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
1657 (id (yas/snippet-next-id) :read-only t)
1658 (control-overlay nil)
1660 ;; stacked expansion: the `previous-active-field' slot saves the
1661 ;; active field where the child expansion took place
1662 previous-active-field
1665 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
1675 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
1681 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
1685 (defun yas/apply-transform (field-or-mirror field)
1686 "Calculate the value of the field/mirror. If there's a transform
1687 for this field, apply it. Otherwise, returned nil."
1688 (let* ((yas/text (yas/field-text-for-display field))
1690 (yas/modified-p (yas/field-modified-p field))
1691 (yas/moving-away-p nil)
1692 (transform (if (yas/mirror-p field-or-mirror)
1693 (yas/mirror-transform field-or-mirror)
1694 (yas/field-transform field-or-mirror)))
1695 (start-point (if (yas/mirror-p field-or-mirror)
1696 (yas/mirror-start field-or-mirror)
1697 (yas/field-start field-or-mirror)))
1698 (transformed (and transform
1700 (goto-char start-point)
1701 (yas/eval-string transform)))))
1704 (defsubst yas/replace-all (from to &optional text)
1705 "Replace all occurance from FROM to TO.
1707 With optional string TEXT do it in that string."
1709 (replace-regexp-in-string (regexp-quote from) to text t t)
1710 (goto-char (point-min))
1711 (while (search-forward from nil t)
1712 (replace-match to t t text))))
1714 (defun yas/snippet-find-field (snippet number)
1715 (find-if #'(lambda (field)
1716 (eq number (yas/field-number field)))
1717 (yas/snippet-fields snippet)))
1719 (defun yas/snippet-sort-fields (snippet)
1720 "Sort the fields of SNIPPET in navigation order."
1721 (setf (yas/snippet-fields snippet)
1722 (sort (yas/snippet-fields snippet)
1723 '(lambda (field1 field2)
1724 (yas/snippet-field-compare field1 field2)))))
1726 (defun yas/snippet-field-compare (field1 field2)
1727 "Compare two fields. The field with a number is sorted first.
1728 If they both have a number, compare through the number. If neither
1729 have, compare through the field's start point"
1730 (let ((n1 (yas/field-number field1))
1731 (n2 (yas/field-number field2)))
1738 (< (yas/field-start field1)
1739 (yas/field-start field2))))))
1741 (defun yas/field-probably-deleted-p (snippet field)
1742 "Guess if SNIPPET's FIELD should be skipped."
1743 (and (zerop (- (yas/field-start field) (yas/field-end field)))
1744 (or (yas/field-parent-field field)
1745 (and (eq field (car (last (yas/snippet-fields snippet))))
1746 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))))
1748 (defun yas/snippets-at-point (&optional all-snippets)
1749 "Return a sorted list of snippets at point, most recently
1752 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
1753 (overlay-get ov 'yas/snippet))
1755 (overlays-in (point-min) (point-max))
1756 (overlays-at (point))))))
1758 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
1760 (defun yas/next-field-or-maybe-expand ()
1761 "Try to expand a snippet at a key before point, otherwise
1762 delegate to `yas/next-field'."
1764 (if yas/triggers-in-field
1765 (let ((yas/fallback-behavior 'return-nil)
1766 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
1768 (unless (yas/expand-1 active-field)
1772 (defun yas/next-field (&optional arg)
1773 "Navigate to next field. If there's none, exit the snippet."
1777 (snippet (first (yas/snippets-at-point)))
1778 (active-field (overlay-get yas/active-field-overlay 'yas/field))
1779 (live-fields (remove-if #'(lambda (field)
1780 (and (not (eq field active-field))
1781 (yas/field-probably-deleted-p snippet field)))
1782 (yas/snippet-fields snippet)))
1783 (active-field-pos (position active-field live-fields))
1784 (target-pos (and active-field-pos (+ arg active-field-pos)))
1785 (target-field (nth target-pos live-fields)))
1786 ;; First check if we're moving out of a field with a transform
1788 (when (and active-field
1789 (yas/field-transform active-field))
1790 (let* ((yas/moving-away-p t)
1791 (yas/text (yas/field-text-for-display active-field))
1793 (yas/modified-p (yas/field-modified-p active-field)))
1794 ;;; primary field transform: exit call to field-transform
1795 (yas/eval-string (yas/field-transform active-field))))
1796 ;; Now actually move...
1797 (cond ((>= target-pos (length live-fields))
1798 (yas/exit-snippet snippet))
1800 (yas/move-to-field snippet target-field))
1804 (defun yas/place-overlays (snippet field)
1805 "Correctly place overlays for SNIPPET's FIELD"
1806 (yas/make-move-field-protection-overlays snippet field)
1807 (yas/make-move-active-field-overlay snippet field))
1809 (defun yas/move-to-field (snippet field)
1810 "Update SNIPPET to move to field FIELD.
1812 Also create some protection overlays"
1813 (goto-char (yas/field-start field))
1814 (setf (yas/snippet-active-field snippet) field)
1815 (yas/place-overlays snippet field)
1816 (overlay-put yas/active-field-overlay 'yas/field field)
1817 ;;; primary field transform: first call to snippet transform
1818 (unless (yas/field-modified-p field)
1819 (if (yas/field-update-display field snippet)
1820 (let ((inhibit-modification-hooks t))
1821 (yas/update-mirrors snippet))
1822 (setf (yas/field-modified-p field) nil))))
1824 (defun yas/prev-field ()
1825 "Navigate to prev field. If there's none, exit the snippet."
1827 (yas/next-field -1))
1829 (defun yas/exit-snippet (snippet)
1830 "Goto exit-marker of SNIPPET."
1832 (setf (yas/snippet-force-exit snippet) t)
1833 (goto-char (if (yas/snippet-exit snippet)
1834 (yas/exit-marker (yas/snippet-exit snippet))
1835 (overlay-end (yas/snippet-control-overlay snippet)))))
1837 ;;; Apropos markers-to-points:
1839 ;;; This was found useful for performance reasons, so that an
1840 ;;; excessive number of live markers aren't kept around in the
1841 ;;; `buffer-undo-list'. However, in `markers-to-points', the
1842 ;;; set-to-nil markers can't simply be discarded and replaced with
1843 ;;; fresh ones in `points-to-markers'. The original marker that was
1844 ;;; just set to nil has to be reused.
1846 ;;; This shouldn't bring horrible problems with undo/redo, but it
1850 (defun yas/markers-to-points (snippet)
1851 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
1852 where POINT is the original position of the marker and MARKER is
1853 the original marker object with the position set to nil."
1854 (dolist (field (yas/snippet-fields snippet))
1855 (let ((start (marker-position (yas/field-start field)))
1856 (end (marker-position (yas/field-end field))))
1857 (set-marker (yas/field-start field) nil)
1858 (set-marker (yas/field-end field) nil)
1859 (setf (yas/field-start field) (cons start (yas/field-start field)))
1860 (setf (yas/field-end field) (cons end (yas/field-end field))))
1861 (dolist (mirror (yas/field-mirrors field))
1862 (let ((start (marker-position (yas/mirror-start mirror)))
1863 (end (marker-position (yas/mirror-end mirror))))
1864 (set-marker (yas/mirror-start mirror) nil)
1865 (set-marker (yas/mirror-end mirror) nil)
1866 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
1867 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
1868 (let ((snippet-exit (yas/snippet-exit snippet)))
1870 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
1871 (set-marker (yas/exit-marker snippet-exit) nil)
1872 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
1874 (defun yas/points-to-markers (snippet)
1875 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
1876 is done by setting MARKER to POINT with `set-marker'."
1877 (dolist (field (yas/snippet-fields snippet))
1878 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field)) (car (yas/field-start field))))
1879 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field)) (car (yas/field-end field))))
1880 (dolist (mirror (yas/field-mirrors field))
1881 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror)) (car (yas/mirror-start mirror))))
1882 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror)) (car (yas/mirror-end mirror))))))
1883 (let ((snippet-exit (yas/snippet-exit snippet)))
1885 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit)) (car (yas/exit-marker snippet-exit)))))))
1887 (defun yas/commit-snippet (snippet &optional no-hooks)
1888 "Commit SNIPPET, but leave point as it is. This renders the
1889 snippet as ordinary text.
1891 Return a buffer position where the point should be placed if
1892 exiting the snippet.
1894 NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
1896 (let ((control-overlay (yas/snippet-control-overlay snippet))
1900 ;; Save the end of the moribund snippet in case we need to revive it
1901 ;; its original expansion.
1903 (when (and control-overlay
1904 (overlay-buffer control-overlay))
1905 (setq yas/snippet-beg (overlay-start control-overlay))
1906 (setq yas/snippet-end (overlay-end control-overlay))
1907 (delete-overlay control-overlay))
1909 (let ((inhibit-modification-hooks t))
1910 (when yas/active-field-overlay
1911 (delete-overlay yas/active-field-overlay))
1912 (when yas/field-protection-overlays
1913 (mapc #'delete-overlay yas/field-protection-overlays)))
1915 ;; stacked expansion: if the original expansion took place from a
1916 ;; field, make sure we advance it here at least to
1917 ;; `yas/snippet-end'...
1919 (let ((previous-field (yas/snippet-previous-active-field snippet)))
1920 (when (and yas/snippet-end previous-field)
1921 (yas/advance-end-maybe previous-field yas/snippet-end)))
1923 ;; Convert all markers to points,
1925 (yas/markers-to-points snippet)
1927 ;; Take care of snippet revival
1929 (if yas/snippet-revival
1930 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
1932 ;; Dismember the snippet... this is useful if we get called
1933 ;; again from `yas/take-care-of-redo'....
1934 (setf (yas/snippet-fields snippet) nil))
1936 ;; XXX: `yas/after-exit-snippet-hook' should be run with
1937 ;; `yas/snippet-beg' and `yas/snippet-end' bound. That might not
1938 ;; be the case if the main overlay had somehow already
1939 ;; disappeared, which sometimes happens when the snippet's messed
1942 (unless no-hooks (run-hooks 'yas/after-exit-snippet-hook)))
1944 (message "[yas] snippet exited."))
1946 (defun yas/check-commit-snippet ()
1947 "Checks if point exited the currently active field of the
1948 snippet, if so cleans up the whole snippet up."
1949 (let* ((snippets (yas/snippets-at-point 'all-snippets))
1950 (snippets-left snippets))
1951 (dolist (snippet snippets)
1952 (let ((active-field (yas/snippet-active-field snippet)))
1953 (cond ((or (prog1 (yas/snippet-force-exit snippet)
1954 (setf (yas/snippet-force-exit snippet) nil))
1955 (not (and active-field (yas/field-contains-point-p active-field))))
1956 (setq snippets-left (delete snippet snippets-left))
1957 (yas/commit-snippet snippet snippets-left))
1959 (or (not yas/active-field-overlay)
1960 (not (overlay-buffer yas/active-field-overlay))))
1962 ;; stacked expansion: this case is mainly for recent
1963 ;; snippet exits that place us back int the field of
1967 (yas/move-to-field snippet active-field)
1968 (yas/update-mirrors snippet)))
1971 (unless snippets-left
1972 (remove-hook 'post-command-hook 'yas/post-command-handler 'local)
1973 (remove-hook 'pre-command-hook 'yas/pre-command-handler 'local))))
1975 (defun yas/field-contains-point-p (field &optional point)
1976 (let ((point (or point
1978 (and (>= point (yas/field-start field))
1979 (<= point (yas/field-end field)))))
1981 (defun yas/field-text-for-display (field)
1982 "Return the propertized display text for field FIELD. "
1983 (buffer-substring (yas/field-start field) (yas/field-end field)))
1985 (defun yas/undo-in-progress ()
1986 "True if some kind of undo is in progress"
1987 (or undo-in-progress
1988 (eq this-command 'undo)
1989 (eq this-command 'redo)))
1991 (defun yas/make-control-overlay (snippet start end)
1992 "Creates the control overlay that surrounds the snippet and
1994 (let ((overlay (make-overlay start
1999 (overlay-put overlay 'keymap yas/keymap)
2000 (overlay-put overlay 'yas/snippet snippet)
2003 (defun yas/skip-and-clear-or-delete-char (&optional field)
2004 "Clears unmodified field if at field start, skips to next tab.
2006 Otherwise deletes a character normally by calling `delete-char'."
2008 (let ((field (or field
2009 (and yas/active-field-overlay
2010 (overlay-buffer yas/active-field-overlay)
2011 (overlay-get yas/active-field-overlay 'yas/field)))))
2013 (not (yas/field-modified-p field))
2014 (eq (point) (marker-position (yas/field-start field))))
2015 (yas/skip-and-clear field)
2018 (call-interactively 'delete-char)))))
2020 (defun yas/skip-and-clear (field)
2021 "Deletes the region of FIELD and sets it modified state to t"
2022 (setf (yas/field-modified-p field) t)
2023 (delete-region (yas/field-start field) (yas/field-end field)))
2025 (defun yas/make-move-active-field-overlay (snippet field)
2026 "Place the active field overlay in SNIPPET's FIELD.
2028 Move the overlay, or create it if it does not exit."
2029 (if (and yas/active-field-overlay
2030 (overlay-buffer yas/active-field-overlay))
2031 (move-overlay yas/active-field-overlay
2032 (yas/field-start field)
2033 (yas/field-end field))
2034 (setq yas/active-field-overlay
2035 (make-overlay (yas/field-start field)
2036 (yas/field-end field)
2038 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
2039 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
2040 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
2041 (overlay-put yas/active-field-overlay 'insert-in-front-hooks '(yas/on-field-overlay-modification))
2042 (overlay-put yas/active-field-overlay 'insert-behind-hooks '(yas/on-field-overlay-modification))))
2044 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
2045 "Clears the field and updates mirrors, conditionally.
2047 Only clears the field if it hasn't been modified and it point it
2048 at field start. This hook doesn't do anything if an undo is in
2050 (unless (yas/undo-in-progress)
2051 (let ((field (overlay-get yas/active-field-overlay 'yas/field)))
2053 (yas/advance-end-maybe field (overlay-end overlay))
2054 ;;; primary field transform: normal calls to expression
2055 (let ((saved-point (point)))
2056 (yas/field-update-display field (car (yas/snippets-at-point)))
2057 (goto-char saved-point))
2058 (yas/update-mirrors (car (yas/snippets-at-point))))
2060 (when (and (not after?)
2061 (not (yas/field-modified-p field))
2062 (eq (point) (if (markerp (yas/field-start field))
2063 (marker-position (yas/field-start field))
2064 (yas/field-start field))))
2065 (yas/skip-and-clear field))
2066 (setf (yas/field-modified-p field) t))))))
2068 ;;; Apropos protection overlays:
2070 ;;; These exist for nasty users who will try to delete parts of the
2071 ;;; snippet outside the active field. Actual protection happens in
2072 ;;; `yas/on-protection-overlay-modification'.
2074 ;;; Currently this signals an error which inhibits the command. For
2075 ;;; commands that move point (like `kill-line'), point is restored in
2076 ;;; the `yas/post-command-handler' using a global
2077 ;;; `yas/protection-violation' variable.
2079 ;;; Alternatively, I've experimented with an implementation that
2080 ;;; commits the snippet before actually calling `this-command'
2081 ;;; interactively, and then signals an eror, which is ignored. but
2082 ;;; blocks all other million modification hooks. This presented some
2083 ;;; problems with stacked expansion.
2086 (defun yas/make-move-field-protection-overlays (snippet field)
2087 "Place protection overlays surrounding SNIPPET's FIELD.
2089 Move the overlays, or create them if they do not exit."
2090 (let ((start (yas/field-start field))
2091 (end (yas/field-end field)))
2092 ;; First check if the (1+ end) is contained in the buffer,
2093 ;; otherwise we'll have to do a bit of cheating and silently
2094 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
2095 ;; when using stacked expansion
2097 (when (< (buffer-size) end)
2099 (let ((inhibit-modification-hooks t))
2100 (goto-char (point-max))
2102 ;; go on to normal overlay creation/moving
2104 (cond ((and yas/field-protection-overlays
2105 (every #'overlay-buffer yas/field-protection-overlays))
2106 (move-overlay (first yas/field-protection-overlays) (1- start) start)
2107 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
2109 (setq yas/field-protection-overlays
2110 (list (make-overlay (1- start) start nil t nil)
2111 (make-overlay end (1+ end) nil t nil)))
2112 (dolist (ov yas/field-protection-overlays)
2113 (overlay-put ov 'face 'yas/field-debug-face)
2114 (overlay-put ov 'yas/snippet snippet)
2115 ;; (overlay-put ov 'evaporate t)
2116 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
2118 (defvar yas/protection-violation nil
2119 "When non-nil, signals attempts to erronesly exit or modify the snippet.
2121 Functions in the `post-command-hook', for example
2122 `yas/post-command-handler' can check it and reset its value to nil. The variables value is the point where the violation originated")
2124 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
2125 "Signals a snippet violation, then issues error.
2127 The error should be ignored in `debug-ignored-errors'"
2128 (cond ((not (or after?
2129 (yas/undo-in-progress)))
2130 (setq yas/protection-violation (point))
2131 (error "Exit the snippet first!"))))
2133 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
2135 ;;; Apropos stacked expansion:
2137 ;;; the parent snippet does not run its fields modification hooks
2138 ;;; (`yas/on-field-overlay-modification' and
2139 ;;; `yas/on-protection-overlay-modification') while the child snippet
2140 ;;; is active. This means, among other things, that the mirrors of the
2141 ;;; parent snippet are not updated, this only happening when one exits
2142 ;;; the child snippet.
2144 ;;; Unfortunately, this also puts some ugly (and not fully-tested)
2145 ;;; bits of code in `yas/expand-snippet' and
2146 ;;; `yas/commit-snippet'. I've tried to mark them with "stacked
2149 ;;; This was thought to be safer in in an undo/redo perpective, but
2150 ;;; maybe the correct implementation is to make the globals
2151 ;;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
2152 ;;; snippet-local and be active even while the child snippet is
2153 ;;; running. This would mean a lot of overlay modification hooks
2154 ;;; running, but if managed correctly (including overlay priorities)
2155 ;;; they should account for all situations...
2158 (defun yas/expand-snippet (start end template &optional snippet-vars)
2159 "Expand snippet at current point. Text between START and END
2160 will be deleted before inserting template."
2161 (run-hooks 'yas/before-expand-snippet-hook)
2164 ;; stacked expansion: shoosh the overlay modification hooks
2166 (let ((key (buffer-substring-no-properties start end))
2167 (inhibit-modification-hooks t)
2168 (column (current-column))
2171 ;; Delete the trigger key, this *does* get undo-recorded.
2173 (delete-region start end)
2175 ;; Narrow the region down to the template, shoosh the
2176 ;; `buffer-undo-list', and create the snippet, the new snippet
2177 ;; updates its mirrors once, so we are left with some plain text.
2178 ;; The undo action for deleting this plain text will get recorded
2179 ;; at the end of this function.
2181 (narrow-to-region start start)
2182 (let ((buffer-undo-list t))
2183 ;; snippet creation might evaluate users elisp, which
2184 ;; might generate errors, so we have to be ready to catch
2185 ;; them mostly to make the undo information
2187 (setq yas/start-column (save-restriction (widen) (current-column)))
2189 (setq yas/deleted-text key)
2190 (setq yas/selected-text (when mark-active key))
2193 (eval `(let ,(read snippet-vars)
2194 (yas/snippet-create (point-min) (point-max))))
2195 (yas/snippet-create (point-min) (point-max))))))
2197 ;; stacked-expansion: This checks for stacked expansion, save the
2198 ;; `yas/previous-active-field' and advance its boudary.
2200 (let ((existing-field (and yas/active-field-overlay
2201 (overlay-buffer yas/active-field-overlay)
2202 (overlay-get yas/active-field-overlay 'yas/field))))
2203 (when existing-field
2204 (setf (yas/snippet-previous-active-field snippet) existing-field)
2205 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
2207 ;; Exit the snippet immediately if no fields
2209 (unless (yas/snippet-fields snippet)
2210 (yas/exit-snippet snippet))
2212 ;; Push two undo actions: the deletion of the inserted contents of
2213 ;; the new snippet (whitout the "key") followed by an apply of
2214 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
2216 (let ((start (overlay-start (yas/snippet-control-overlay snippet)))
2217 (end (overlay-end (yas/snippet-control-overlay snippet))))
2218 (push (cons start end) buffer-undo-list)
2219 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
2221 ;; Now, move to the first field
2223 (let ((first-field (car (yas/snippet-fields snippet))))
2225 (yas/move-to-field snippet first-field))))
2226 (message "[yas] snippet expanded."))
2228 (defun yas/take-care-of-redo (beg end snippet)
2229 "Commits SNIPPET, which in turn pushes an undo action for
2232 Meant to exit in the `buffer-undo-list'."
2233 ;; slightly optimize: this action is only needed for snippets with
2234 ;; at least one field
2235 (when (yas/snippet-fields snippet)
2236 (yas/commit-snippet snippet 'no-hooks)))
2238 (defun yas/snippet-revive (beg end snippet)
2239 "Revives the SNIPPET and creates a control overlay from BEG to
2242 BEG and END are, we hope, the original snippets boudaries. All
2243 the markers/points exiting existing inside SNIPPET should point
2244 to their correct locations *at the time the snippet is revived*.
2246 After revival, push the `yas/take-care-of-redo' in the
2248 ;; Reconvert all the points to markers
2250 (yas/points-to-markers snippet)
2251 ;; When at least one editable field existed in the zombie snippet,
2252 ;; try to revive the whole thing...
2254 (let ((target-field (or (yas/snippet-active-field snippet)
2255 (car (yas/snippet-fields snippet)))))
2257 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
2258 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
2260 (yas/move-to-field snippet target-field)
2262 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
2263 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
2265 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
2266 buffer-undo-list))))
2268 (defun yas/snippet-create (begin end)
2269 "Creates a snippet from an template inserted between BEGIN and END.
2271 Returns the newly created snippet."
2272 (let ((snippet (yas/make-snippet)))
2274 (yas/snippet-parse-create snippet)
2276 ;; Sort and link each field
2277 (yas/snippet-sort-fields snippet)
2279 ;; Update the mirrors for the first time
2280 (yas/update-mirrors snippet)
2282 ;; Create keymap overlay for snippet
2283 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet (point-min) (point-max)))
2286 (goto-char (point-max))
2289 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
2290 (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
2294 ;;; apropos adjacencies: Once the $-constructs bits like "$n" and
2295 ;;; "${:n" are deleted in the recently expanded snippet, we might
2296 ;;; actually have many fields, mirrors (and the snippet exit) in the
2297 ;;; very same position in the buffer. Therefore we need to single-link
2298 ;;; the fields-or-mirrors-or-exit, which I have called "fom",
2299 ;;; according to their original positions in the buffer.
2301 ;;; Then we have operation `yas/advance-end-maybe' and
2302 ;;; `yas/advance-start-maybe', which conditionally push the starts and
2303 ;;; ends of these foms down the chain.
2305 ;;; This allows for like the printf with the magic ",":
2307 ;;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
2308 ;;; $2${1:$(if (string-match "%" text) "\);" "")}$0
2311 (defun yas/fom-start (fom)
2312 (cond ((yas/field-p fom)
2313 (yas/field-start fom))
2315 (yas/mirror-start fom))
2317 (yas/exit-marker fom))))
2319 (defun yas/fom-end (fom)
2320 (cond ((yas/field-p fom)
2321 (yas/field-end fom))
2323 (yas/mirror-end fom))
2325 (yas/exit-marker fom))))
2327 (defun yas/fom-next (fom)
2328 (cond ((yas/field-p fom)
2329 (yas/field-next fom))
2331 (yas/mirror-next fom))
2333 (yas/exit-next fom))))
2335 (defun yas/calculate-adjacencies (snippet)
2336 "Calculate adjacencies for fields or mirrors of SNIPPET.
2338 This is according to their relative positions in the buffer, and
2339 has to be called before the $-constructs are deleted."
2340 (flet ((yas/fom-set-next-fom (fom nextfom)
2341 (cond ((yas/field-p fom)
2342 (setf (yas/field-next fom) nextfom))
2344 (setf (yas/mirror-next fom) nextfom))
2346 (setf (yas/exit-next fom) nextfom))))
2347 (yas/compare-fom-begs (fom1 fom2)
2348 (> (yas/fom-start fom2) (yas/fom-start fom1)))
2349 (yas/link-foms (fom1 fom2)
2350 (yas/fom-set-next-fom fom1 fom2)))
2351 ;; make some yas/field, yas/mirror and yas/exit soup
2353 (when (yas/snippet-exit snippet)
2354 (push (yas/snippet-exit snippet) soup))
2355 (dolist (field (yas/snippet-fields snippet))
2357 (dolist (mirror (yas/field-mirrors field))
2358 (push mirror soup)))
2361 #'yas/compare-fom-begs))
2363 (reduce #'yas/link-foms soup)))))
2365 (defun yas/advance-end-maybe (fom newend)
2366 "Maybe advance FOM's end to NEWEND if it needs it.
2370 * call `yas/advance-start-maybe' on FOM's next fom.
2372 * in case FOM is field call `yas/advance-end-maybe' on its parent
2374 (when (and fom (< (yas/fom-end fom) newend))
2375 (set-marker (yas/fom-end fom) newend)
2376 (yas/advance-start-maybe (yas/fom-next fom) newend)
2377 (if (and (yas/field-p fom)
2378 (yas/field-parent-field fom))
2379 (yas/advance-end-maybe (yas/field-parent-field fom) newend))))
2381 (defun yas/advance-start-maybe (fom newstart)
2382 "Maybe advance FOM's start to NEWSTART if it needs it.
2384 If it does, also call `yas/advance-end-maybe' on FOM."
2385 (when (and fom (< (yas/fom-start fom) newstart))
2386 (set-marker (yas/fom-start fom) newstart)
2387 (yas/advance-end-maybe fom newstart)))
2389 (defun yas/snippet-parse-create (snippet)
2390 "Parse a recently inserted snippet template, creating all
2391 necessary fields, mirrors and exit points.
2393 Meant to be called in a narrowed buffer, does various passes"
2394 (let ((parse-start (point))
2395 (dollar-regions (list 'reg)))
2396 ;; protect quote and backquote escapes
2398 (yas/protect-escapes nil '(?` ?'))
2399 ;; replace all backquoted expressions
2401 (goto-char parse-start)
2402 (yas/replace-backquotes)
2403 ;; protect escapes again since previous stepds might have
2404 ;; generated more characters needing escapinge
2406 (goto-char parse-start)
2407 (yas/protect-escapes)
2408 ;; parse fields with {}
2410 (goto-char parse-start)
2411 (yas/field-parse-create snippet dollar-regions)
2412 ;; parse simple mirrors and fields
2414 (goto-char parse-start)
2415 (yas/simple-mirror-parse-create snippet dollar-regions)
2416 ;; parse mirror transforms
2418 (goto-char parse-start)
2419 (yas/transform-mirror-parse-create snippet dollar-regions)
2420 ;; calculate adjacencies of fields and mirrors
2422 (yas/calculate-adjacencies snippet)
2423 ;; Delete $-constructs
2425 (yas/delete-regions (copy-list (rest dollar-regions)))
2428 (goto-char parse-start)
2429 (yas/restore-escapes)
2430 ;; update mirrors for the first time
2432 (yas/update-mirrors snippet)
2433 ;; indent the best we can
2435 (goto-char parse-start)
2436 (yas/indent snippet)))
2438 (defun yas/indent (snippet)
2440 (while (re-search-forward "$>" nil t)
2441 (delete-region (match-beginning 0) (match-end 0))
2442 (when (not (eq yas/indent-line 'auto))
2443 (indent-according-to-mode))))
2445 (cond ((eq yas/indent-line 'fixed)
2446 (let* ((indent (if indent-tabs-mode
2447 (concat (make-string (/ column tab-width) ?\t)
2448 (make-string (% column tab-width) ?\ ))
2449 (make-string (current-column) ?\ ))))
2450 (goto-char (point-min))
2451 (while (and (zerop (forward-line))
2452 (= (current-column) 0))
2454 ((eq yas/indent-line 'auto)
2455 (let ((end (set-marker (make-marker) (point-max)))
2456 (indent-first-line-p yas/also-auto-indent-first-line)
2457 (snippet-markers (yas/collect-snippet-markers snippet)))
2460 ;; XXX: Here seems to be the indent problem:
2462 ;; `indent-according-to-mode' uses whatever
2463 ;; `indent-line-function' is available. Some
2464 ;; implementations of these functions delete text
2465 ;; before they insert. If there happens to be a marker
2466 ;; just after the text being deleted, the insertion
2467 ;; actually happens after the marker, which misplaces
2470 ;; This would also happen if we had used overlays with
2471 ;; the `front-advance' property set to nil.
2473 (while (and (zerop (if indent-first-line-p
2476 (setq indent-first-line-p nil))
2480 (goto-char (yas/real-line-beginning))
2481 (let ((trouble-markers (remove-if-not #'(lambda (marker)
2484 (indent-according-to-mode)
2485 (mapc #'(lambda (marker)
2486 (set-marker marker (point)))
2488 (indent-according-to-mode)))
2489 (set-marker end nil))))
2493 (defun yas/collect-snippet-markers (snippet)
2494 "Make a list of all the markers used by SNIPPET."
2496 (dolist (field (yas/snippet-fields snippet))
2497 (push (yas/field-start field) markers)
2498 (push (yas/field-end field) markers)
2499 (dolist (mirror (yas/field-mirrors field))
2500 (push (yas/mirror-start mirror) markers)
2501 (push (yas/mirror-end mirror) markers)))
2502 (let ((snippet-exit (yas/snippet-exit snippet)))
2503 (when (and snippet-exit
2504 (marker-buffer (yas/exit-marker snippet-exit)))
2505 (push (yas/exit-marker snippet-exit) markers)))
2508 (defun yas/real-line-beginning ()
2509 (let ((c (char-after (line-beginning-position)))
2510 (n (line-beginning-position)))
2511 (while (or (eql c ?\ )
2514 (setq c (char-after n)))
2517 (defun yas/escape-string (escaped)
2518 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
2520 (defun yas/protect-escapes (&optional text escaped)
2521 "Protect all escaped characters with their numeric ASCII value.
2523 With optional string TEXT do it in string instead of buffer."
2524 (let ((changed-text text)
2525 (text-provided-p text))
2526 (mapc #'(lambda (escaped)
2528 (yas/replace-all (concat "\\" (char-to-string escaped))
2529 (yas/escape-string escaped)
2530 (when text-provided-p changed-text))))
2531 (or escaped yas/escaped-characters))
2534 (defun yas/restore-escapes (&optional text escaped)
2535 "Restore all escaped characters from their numeric ASCII value.
2537 With optional string TEXT do it in string instead of the buffer."
2538 (let ((changed-text text)
2539 (text-provided-p text))
2540 (mapc #'(lambda (escaped)
2542 (yas/replace-all (yas/escape-string escaped)
2543 (char-to-string escaped)
2544 (when text-provided-p changed-text))))
2545 (or escaped yas/escaped-characters))
2548 (defun yas/replace-backquotes ()
2549 "Replace all the \"`(lisp-expression)`\"-style expression
2550 with their evaluated value"
2551 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
2552 (let ((transformed (yas/eval-string (yas/restore-escapes (match-string 1)))))
2553 (goto-char (match-end 0))
2554 (when transformed (insert transformed))
2555 (delete-region (match-beginning 0) (match-end 0)))))
2557 (defun yas/scan-sexps (from count)
2559 (with-syntax-table (standard-syntax-table)
2560 (scan-sexps from count))
2564 (defun yas/make-marker (pos)
2565 "Create a marker at POS with `nil' `marker-insertion-type'"
2566 (let ((marker (set-marker (make-marker) pos)))
2567 (set-marker-insertion-type marker nil)
2570 (defun yas/add-to-list (l e)
2574 (defun yas/field-parse-create (snippet dollar-regions &optional parent-field)
2575 "Parse most field expression, except for the simple one \"$n\".
2577 The following count as a field:
2579 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
2580 * \"${n: text$(expression)}, the same with a lisp expression;
2581 * the same as above but unnumbered, (no N:) and number is calculated automatically.
2583 When multiple expressions are found, only the last one counts."
2585 (while (re-search-forward yas/field-regexp nil t)
2586 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
2587 (number (and (match-string-no-properties 1)
2588 (string-to-number (match-string-no-properties 1))))
2589 (brand-new-field (and real-match-end-0
2590 (not (save-match-data
2591 (eq (string-match "$[ \t\n]*(" (match-string-no-properties 2)) 0)))
2592 (not (and number (zerop number)))
2593 (yas/make-field number
2594 (yas/make-marker (match-beginning 2))
2595 (yas/make-marker (1- real-match-end-0))
2597 (when brand-new-field
2598 (yas/add-to-list dollar-regions
2599 (cons (1- real-match-end-0) real-match-end-0))
2600 (yas/add-to-list dollar-regions
2601 (cons (match-beginning 0) (match-beginning 2)))
2602 (push brand-new-field (yas/snippet-fields snippet))
2605 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
2606 (goto-char (point-min))
2607 (yas/field-parse-create snippet dollar-regions brand-new-field)))))))
2610 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
2611 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
2612 (when real-match-end-1
2613 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1) real-match-end-1)))
2614 (setf (yas/field-transform parent-field) (yas/restore-escapes lisp-expression-string)))
2615 (yas/add-to-list dollar-regions
2616 (cons (match-beginning 0) real-match-end-1))))))))
2618 (defun yas/transform-mirror-parse-create (snippet dollar-regions)
2619 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
2620 (while (re-search-forward yas/transform-mirror-regexp nil t)
2621 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
2622 (number (string-to-number (match-string-no-properties 1)))
2624 (not (zerop number))
2625 (yas/snippet-find-field snippet number))))
2626 (when (and real-match-end-0
2628 (push (yas/make-mirror (yas/make-marker (match-beginning 0))
2629 (yas/make-marker (match-beginning 0))
2630 (yas/restore-escapes (buffer-substring-no-properties (match-beginning 2)
2631 (1- real-match-end-0))))
2632 (yas/field-mirrors field))
2633 (yas/add-to-list dollar-regions
2634 (cons (match-beginning 0) real-match-end-0))))))
2636 (defun yas/simple-mirror-parse-create (snippet dollar-regions)
2637 "Parse the simple \"$n\" mirrors and the exit-marker."
2638 (while (re-search-forward yas/simple-mirror-regexp nil t)
2639 (let ((number (string-to-number (match-string-no-properties 1))))
2640 (cond ((zerop number)
2642 (setf (yas/snippet-exit snippet)
2643 (yas/make-exit (yas/make-marker (match-end 0))))
2645 (goto-char (match-beginning 0))
2646 (when (and yas/wrap-around-region yas/selected-text)
2647 (insert yas/selected-text))
2648 (yas/add-to-list dollar-regions
2649 (cons (point) (yas/exit-marker (yas/snippet-exit snippet))))))
2651 (let ((field (yas/snippet-find-field snippet number)))
2653 (push (yas/make-mirror (yas/make-marker (match-beginning 0))
2654 (yas/make-marker (match-beginning 0))
2656 (yas/field-mirrors field))
2657 (push (yas/make-field number
2658 (yas/make-marker (match-beginning 0))
2659 (yas/make-marker (match-beginning 0))
2661 (yas/snippet-fields snippet))))
2662 (yas/add-to-list dollar-regions
2663 (cons (match-beginning 0) (match-end 0))))))))
2665 (defun yas/delete-regions (regions)
2666 "Sort disjuct REGIONS by start point, then delete from the back."
2667 (mapc #'(lambda (reg)
2668 (delete-region (car reg) (cdr reg)))
2671 (>= (car r1) (car r2))))))
2673 (defun yas/update-mirrors (snippet)
2674 "Updates all the mirrors of SNIPPET."
2676 (dolist (field (yas/snippet-fields snippet))
2677 (dolist (mirror (yas/field-mirrors field))
2678 ;; stacked expansion: I added an `inhibit-modification-hooks'
2679 ;; here, for safety, may need to remove if we the mechanism is
2682 (let ((inhibit-modification-hooks t))
2683 (yas/mirror-update-display mirror field)
2684 ;; `yas/place-overlays' is needed if the active field and
2685 ;; protected overlays have been changed because of insertions
2686 ;; in `yas/mirror-update-display'
2688 (when (eq field (yas/snippet-active-field snippet))
2689 (yas/place-overlays snippet field)))))))
2691 (defun yas/mirror-update-display (mirror field)
2692 "Update MIRROR according to FIELD (and mirror transform)."
2693 (let ((reflection (or (yas/apply-transform mirror field)
2694 (yas/field-text-for-display field))))
2695 (when (and reflection
2696 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror) (yas/mirror-end mirror)))))
2697 (goto-char (yas/mirror-start mirror))
2699 (if (> (yas/mirror-end mirror) (point))
2700 (delete-region (point) (yas/mirror-end mirror))
2701 (set-marker (yas/mirror-end mirror) (point))
2702 (yas/advance-start-maybe (yas/mirror-next mirror) (point))))))
2704 (defun yas/field-update-display (field snippet)
2705 "Much like `yas/mirror-update-display', but for fields"
2706 (when (yas/field-transform field)
2707 (let ((inhibit-modification-hooks t)
2708 (transformed (yas/apply-transform field field))
2710 (when (and transformed
2711 (not (string= transformed (buffer-substring-no-properties (yas/field-start field) (yas/field-end field)))))
2712 (setf (yas/field-modified-p field) t)
2713 (goto-char (yas/field-start field))
2714 (insert transformed)
2715 (if (> (yas/field-end field) (point))
2716 (delete-region (point) (yas/field-end field))
2717 (set-marker (yas/field-end field) (point))
2718 (yas/advance-start-maybe (yas/field-next field) (point)))
2721 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2722 ;; Pre- and post-command hooks
2724 (defun yas/pre-command-handler () )
2726 (defun yas/post-command-handler ()
2727 "Handles various yasnippet conditions after each command."
2728 (cond (yas/protection-violation
2729 (goto-char yas/protection-violation)
2730 (setq yas/protection-violation nil))
2731 ((eq 'undo this-command)
2733 ;; After undo revival the correct field is sometimes not
2734 ;; restored correctly, this condition handles that
2736 (let* ((snippet (car (yas/snippets-at-point)))
2737 (target-field (and snippet
2738 (find-if-not #'(lambda (field)
2739 (yas/field-probably-deleted-p snippet field))
2741 (cons (yas/snippet-active-field snippet)
2742 (yas/snippet-fields snippet)))))))
2744 (yas/move-to-field snippet target-field))))
2745 ((not (yas/undo-in-progress))
2746 ;; When not in an undo, check if we must commit the snippet (use exited it).
2747 (yas/check-commit-snippet))))
2749 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2750 ;; Debug functions. Use (or change) at will whenever needed.
2753 (defun yas/debug-some-vars ()
2754 "Debug snippets, fields, mirrors and the `buffer-undo-list'."
2756 (with-output-to-temp-buffer "*YASnippet trace*"
2757 (princ "Interesting YASnippet vars: \n\n")
2759 (princ (format "\nPost command hook: %s\n" post-command-hook))
2760 (princ (format "\nPre command hook: %s\n" pre-command-hook))
2762 (princ (format "%s live snippets in total\n" (length (yas/snippets-at-point (quote all-snippets)))))
2763 (princ (format "%s overlays in buffer:\n\n" (length (overlays-in (point-min) (point-max)))))
2764 (princ (format "%s live snippets at point:\n\n" (length (yas/snippets-at-point))))
2767 (dolist (snippet (yas/snippets-at-point))
2768 (princ (format "\tsid: %d control overlay from %d to %d\n"
2769 (yas/snippet-id snippet)
2770 (overlay-start (yas/snippet-control-overlay snippet))
2771 (overlay-end (yas/snippet-control-overlay snippet))))
2772 (princ (format "\tactive field: %d from %s to %s covering \"%s\"\n"
2773 (yas/field-number (yas/snippet-active-field snippet))
2774 (marker-position (yas/field-start (yas/snippet-active-field snippet)))
2775 (marker-position (yas/field-end (yas/snippet-active-field snippet)))
2776 (buffer-substring-no-properties (yas/field-start (yas/snippet-active-field snippet)) (yas/field-end (yas/snippet-active-field snippet)))))
2777 (when (yas/snippet-exit snippet)
2778 (princ (format "\tsnippet-exit: at %s next: %s\n"
2779 (yas/exit-marker (yas/snippet-exit snippet))
2780 (yas/exit-next (yas/snippet-exit snippet)))))
2781 (dolist (field (yas/snippet-fields snippet))
2782 (princ (format "\tfield: %d from %s to %s covering \"%s\" next: %s\n"
2783 (yas/field-number field)
2784 (marker-position (yas/field-start field))
2785 (marker-position (yas/field-end field))
2786 (buffer-substring-no-properties (yas/field-start field) (yas/field-end field))
2787 (yas/debug-format-fom-concise (yas/field-next field))))
2788 (dolist (mirror (yas/field-mirrors field))
2789 (princ (format "\t\tmirror: from %s to %s covering \"%s\" next: %s\n"
2790 (marker-position (yas/mirror-start mirror))
2791 (marker-position (yas/mirror-end mirror))
2792 (buffer-substring-no-properties (yas/mirror-start mirror) (yas/mirror-end mirror))
2793 (yas/debug-format-fom-concise (yas/mirror-next mirror)))))))
2795 (princ (format "\nUndo is %s and point-max is %s.\n"
2796 (if (eq buffer-undo-list t)
2800 (unless (eq buffer-undo-list t)
2801 (princ (format "Undpolist has %s elements. First 10 elements follow:\n" (length buffer-undo-list)))
2802 (let ((first-ten (subseq buffer-undo-list 0 19)))
2803 (dolist (undo-elem first-ten)
2804 (princ (format "%2s: %s\n" (position undo-elem first-ten) (truncate-string-to-width (format "%s" undo-elem) 70))))))))
2806 (defun yas/debug-format-fom-concise (fom)
2808 (cond ((yas/field-p fom)
2809 (format "field %d from %d to %d"
2810 (yas/field-number fom)
2811 (marker-position (yas/field-start fom))
2812 (marker-position (yas/field-end fom))))
2814 (format "mirror from %d to %d"
2815 (marker-position (yas/mirror-start fom))
2816 (marker-position (yas/mirror-end fom))))
2818 (format "snippet exit at %d"
2819 (marker-position (yas/fom-start fom)))))))
2822 (defun yas/exterminate-package ()
2824 (yas/global-mode -1)
2826 (mapatoms #'(lambda (atom)
2827 (when (string-match "yas/" (symbol-name atom))
2830 (defun yas/debug-test (&optional quiet)
2832 (yas/load-directory (or (and (listp yas/root-directory)
2833 (first yas/root-directory))
2835 "~/Source/yasnippet/snippets/"))
2836 (set-buffer (switch-to-buffer "*YAS TEST*"))
2837 (mapc #'yas/commit-snippet (yas/snippets-at-point 'all-snippets))
2839 (setq buffer-undo-list nil)
2840 (setq undo-in-progress nil)
2847 (add-hook 'post-command-hook 'yas/debug-some-vars 't 'local)))
2849 (provide 'yasnippet)
2851 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2852 ;; Monkey patching for other functions that's causing
2853 ;; problems to yasnippet. For details on why I patch
2854 ;; those functions, refer to
2855 ;; http://code.google.com/p/yasnippet/wiki/MonkeyPatching
2856 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2857 (defadvice c-neutralize-syntax-in-CPP
2858 (around yas-mp/c-neutralize-syntax-in-CPP activate)
2859 "Adviced `c-neutralize-syntax-in-CPP' to properly
2860 handle the end-of-buffer error fired in it by calling
2861 `forward-char' at the end of buffer."
2864 (error (message (error-message-string err)))))
2866 ;; disable c-electric-* serial command in YAS fields
2867 (add-hook 'c-mode-common-hook
2869 (make-variable-buffer-local 'yas/keymap)
2870 (dolist (k '(":" ">" ";" "<" "{" "}"))
2871 (define-key yas/keymap
2872 k 'self-insert-command))))
2875 ;;; yasnippet.el ends here