]> code.delx.au - gnu-emacs-elpa/blobdiff - yasnippet.el
bugfix: fix #245
[gnu-emacs-elpa] / yasnippet.el
index 478451503be97cdb1f66758ad8709a190d01bec7..305cae913aabd4e25c1360f91054fde2aef6cf96 100644 (file)
@@ -6,9 +6,9 @@
 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
 ;; Version: 0.7.0
 ;; Package-version: 0.7.0
-;; X-URL: http://code.google.com/p/yasnippet/
+;; X-URL: http://github.com/capitaomorte/yasnippet
 ;; Keywords: convenience, emulation
-;; URL: http://code.google.com/p/yasnippet/
+;; URL: http://github.com/capitaomorte/yasnippet
 ;; EmacsWiki: YaSnippetMode
 
 ;; This file is free software; you can redistribute it and/or modify
 
 ;; Basic steps to setup:
 ;;
-;;   1. In your .emacs file:
-;;        (add-to-list 'load-path "/dir/to/yasnippet.el")
-;;        (require 'yasnippet)
-;;   2. Place the `snippets' directory somewhere.  E.g: ~/.emacs.d/snippets
-;;   3. In your .emacs file
-;;        (setq yas/snippet-dirs "~/.emacs/snippets")
-;;        (yas/load-directory yas/snippet-dirs)
-;;   4. To enable the YASnippet menu and tab-trigger expansion
-;;        M-x yas/minor-mode
-;;   5. To globally enable the minor mode in *all* buffers
-;;        M-x yas/global-mode
+;;    (add-to-list 'load-path
+;;                 "~/.emacs.d/plugins/yasnippet")
+;;    (require 'yasnippet)
+;;    (yas/global-mode 1)
 ;;
-;;   Steps 4. and 5. are optional, you don't have to use the minor
-;;   mode to use YASnippet.
 ;;
 ;;   Interesting variables are:
 ;;
 ;;           when used for bulk (re)loading of snippets (at startup or
 ;;           via `yas/reload-all'), directories appearing earlier in
 ;;           the list shadow other dir's snippets. Also, the first
-;;           directory is taken as the default for storing the user's new snippets.
+;;           directory is taken as the default for storing the user's
+;;           new snippets.
 ;;
-;;       `yas/mode-symbol'
+;;           The deprecated `yas/root-directory' aliases this variable
+;;           for backward-compatibility.
+;;
+;;       `yas/extra-modes'
 ;;
 ;;           A local variable that you can set in a hook to override
 ;;           snippet-lookup based on major mode. It is a a symbol (or
@@ -64,6 +59,9 @@
 ;;           `yas/snippet-dirs' and is used for deciding which
 ;;           snippets to consider for the active buffer.
 ;;
+;;           Deprecated `yas/mode-symbol' aliases this variable for
+;;           backward-compatibility.
+;;
 ;;   Major commands are:
 ;;
 ;;       M-x yas/expand
 ;;   `custom-set-variables' is executed in your .emacs file.
 ;;
 ;;   For more information and detailed usage, refer to the project page:
-;;      http://code.google.com/p/yasnippet/
+;;      http://github.com/capitaomorte/yasnippet
 
 ;;; Code:
 
 (require 'cl)
-(require 'assoc)
 (require 'easymenu)
 (require 'help-mode)
 
   "Yet Another Snippet extension"
   :group 'editing)
 
-;;;###autoload
-(defcustom yas/snippet-dirs nil
+(defvar yas/load-file-name load-file-name
+  "Store the filename that yasnippet.el was originally loaded from.")
+(defcustom yas/snippet-dirs (remove nil
+                                    (list "~/.emacs.d/snippets"
+                                          (when yas/load-file-name
+                                            (concat (file-name-directory yas/load-file-name) "snippets"))))
   "Directory or list of snippet dirs for each major mode.
 
 The directory where user-created snippets are to be stored. Can
@@ -178,6 +179,9 @@ as the default for storing the user's new snippets."
              (unless (or (not (fboundp 'yas/reload-all))
                          (equal old new))
                (yas/reload-all)))))
+(defun yas/snippet-dirs ()
+  "Returns `yas/snippet-dirs' (which see) as a list."
+  (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
 
 (defcustom yas/prompt-functions '(yas/x-prompt
@@ -287,7 +291,7 @@ Can also be a list of strings."
            (if (fboundp 'yas/init-yas-in-snippet-keymap)
                (yas/init-yas-in-snippet-keymap))))
 
-(defcustom yas/skip-and-clear-key "C-d"
+(defcustom yas/skip-and-clear-key '("C-d" "<delete>" "<deletechar>")
   "The key to clear the currently active field.
 
 Value is a string that is converted to the internal Emacs key
@@ -345,7 +349,7 @@ This affects `yas/insert-snippet', `yas/visit-snippet-file'"
   :type 'boolean
   :group 'yasnippet)
 
-(defcustom yas/use-menu 'real-modes
+(defcustom yas/use-menu 'abbreviate
   "Display a YASnippet menu in the menu bar.
 
 When non-nil, submenus for each snippet table will be listed
@@ -355,7 +359,7 @@ under the menu \"Yasnippet\".
 corresponds to a major mode are listed.
 
 - If set to `abbreviate', only the current major-mode
-menu and the modes set in `yas/mode-symbol' are listed.
+menu and the modes set in `yas/extra-modes' are listed.
 
 Any other non-nil value, every submenu is listed."
   :type '(choice (const :tag "Full"  t)
@@ -383,14 +387,6 @@ An error string \"[yas] error\" is returned instead."
   :type 'boolean
   :group 'yasnippet)
 
-(defcustom yas/ignore-filenames-as-triggers nil
-  "If non-nil, don't derive tab triggers from filenames.
-
-This means a snippet without a \"# key:'\ directive wont have a
-tab trigger."
-  :type 'boolean
-  :group 'yasnippet)
-
 (defcustom yas/visit-from-menu nil
   "If non-nil visit snippets's files from menu, instead of expanding them.
 
@@ -398,9 +394,24 @@ This cafn only work when snippets are loaded from files."
   :type 'boolean
   :group 'yasnippet)
 
+(defcustom yas/expand-only-for-last-commands nil
+  "List of `last-command' values to restrict tab-triggering to, or nil.
+
+Leave this set at nil (the default) to be able to trigger an
+expansion simply by placing the cursor after a valid tab trigger,
+using whichever commands.
+
+Optionallly, set this to something like '(self-insert-command) if
+you to wish restrict expansion to only happen when the last
+letter of the snippet tab trigger was typed immediately before
+the trigger key itself."
+  :type '(repeat function)
+  :group 'yasnippet)
+
+;; Only two faces, and one of them shouldn't even be used...
+;;
 (defface yas/field-highlight-face
-  '((((class color) (background light)) (:background "DarkSeaGreen1"))
-    (t (:background "DimGrey")))
+  '((t (:inherit 'region)))
   "The face used to highlight the currently active field of a snippet"
   :group 'yasnippet)
 
@@ -429,14 +440,20 @@ This cafn only work when snippets are loaded from files."
     map)
   "The keymap active while a snippet expansion is in progress.")
 
-(defvar yas/key-syntaxes (list "w" "w_" "w_.()" "^ ")
-  "A list of syntax of a key. This list is tried in the order
-to try to find a key. For example, if the list is '(\"w\" \"w_\").
-And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":
+(defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
+  "List of character syntaxes used to find a trigger key before point.
+The list is tried in the order while scanning characters
+backwards from point. For example, if the list is '(\"w\" \"w_\")
+first look for trigger keys which are composed exclusively of
+\"word\"-syntax characters, and then, if that fails, look for
+keys which are either of \"word\" or \"symbol\"
+syntax. Triggering after
 
 foo-bar
 
-will first try \"bar\", if not found, then \"foo-bar\" is tried.")
+will, according to the \"w\" element first try \"bar\". If that
+isn't a trigger key, \"foo-bar\" is tried, respecting a second
+\"w_\" element.")
 
 (defvar yas/after-exit-snippet-hook
   '()
@@ -456,13 +473,15 @@ Attention: These hooks are not run when exiting nested/stackd snippet expansion!
   "Hooks to run just before expanding a snippet.")
 
 (defvar yas/buffer-local-condition
-  '(if (or (fourth (syntax-ppss))
-           (fifth (syntax-ppss)))
+  '(if (and (or (fourth (syntax-ppss))
+                (fifth (syntax-ppss)))
+            (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
        '(require-snippet-condition . force-in-comment)
      t)
   "Snippet expanding condition.
 
-This variable is a lisp form:
+This variable is a lisp form which is evaluated everytime a
+snippet expansion is attemped:
 
     * If it evaluates to nil, no snippets can be expanded.
 
@@ -520,16 +539,12 @@ snippet itself contains a condition that returns the symbol
 (defvar yas/menu-table (make-hash-table)
   "A hash table of MAJOR-MODE symbols to menu keymaps.")
 
-(defun teste ()
-  (interactive)
-  (message "AHAHA!"))
-
 (defvar yas/known-modes
   '(ruby-mode rst-mode markdown-mode)
   "A list of mode which is well known but not part of emacs.")
 
 (defvar yas/escaped-characters
-  '(?\\ ?` ?' ?$ ?} )
+  '(?\\ ?` ?\" ?' ?$ ?} ?{ ?\( ?\))
   "List of characters which *might* need to be escaped.")
 
 (defconst yas/field-regexp
@@ -672,11 +687,6 @@ snippet itself contains a condition that returns the symbol
                 (not yas/good-grace))
           :help "If non-nil don't raise errors in bad embedded eslip in snippets"
           :style toggle :selected yas/good-grace]
-         ["Ignore filenames as triggers"
-          (setq yas/ignore-filenames-as-triggers
-                (not yas/ignore-filenames-as-triggers))
-          :help "If non-nil don't derive tab triggers from filenames"
-          :style toggle :selected yas/ignore-filenames-as-triggers]
          )
         "----"
         ["Load snippets..."  yas/load-directory
@@ -711,42 +721,55 @@ With optional UNBIND-KEY, try to unbind that key from
     (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
 
 (defvar yas/tables (make-hash-table)
-  "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
+  "A hash table of mode symbols to `yas/table' objects.")
+
+(defvar yas/parents (make-hash-table)
+  "A hash table of mode symbols do lists of direct parent mode symbols.
+
+This list is populated when reading the \".yas-parents\" files
+found when traversing snippet directories with
+`yas/load-directory'.
+
+There might be additionalal parenting information stored in the
+`derived-mode-parent' property of some mode symbols, but that is
+not recorded here.")
 
 (defvar yas/direct-keymaps (list)
   "Keymap alist supporting direct snippet keybindings.
 
-This variable is is placed `emulation-mode-map-alists'.
+This variable is is placed in `emulation-mode-map-alists'.
 
-Its elements looks like (TABLE-NAME . KEYMAP) and are
-calculated when loading snippets. TABLE-NAME is a variable
-set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
-all defined direct keybindings to the command
-`yas/expand-from-keymap', which acts similarly to `yas/expand'")
+Its elements looks like (TABLE-NAME . KEYMAP). They're
+instantiated on `yas/reload-all' but KEYMAP is added to only when
+loading snippets. `yas//direct-TABLE-NAME' is then a variable set
+buffer-locally when entering `yas/minor-mode'. KEYMAP binds all
+defined direct keybindings to the command
+`yas/expand-from-keymap' which then which snippet to expand.")
 
 (defun yas/direct-keymaps-reload ()
   "Force reload the direct keybinding for active snippet tables."
   (interactive)
   (setq yas/direct-keymaps nil)
   (maphash #'(lambda (name table)
-               (mapc #'(lambda (table)
-                         (push (cons (intern (format "yas//direct-%s" name))
-                                     (yas/table-direct-keymap table))
-                               yas/direct-keymaps))
-                     (cons table (yas/table-get-all-parents table))))
+               (push (cons (intern (format "yas//direct-%s" name))
+                           (yas/table-direct-keymap table))
+                     yas/direct-keymaps))
            yas/tables))
 
-(defun yas/direct-keymaps-set-vars ()
+(defun yas/modes-to-activate ()
+  "Compute list of mode symbols that are active for `yas/expand'
+and friends."
   (let ((modes-to-activate (list major-mode))
         (mode major-mode))
     (while (setq mode (get mode 'derived-mode-parent))
       (push mode modes-to-activate))
-    (when yas/mode-symbol
-      (push yas/mode-symbol modes-to-activate))
-    (dolist (mode modes-to-activate)
-      (let ((name (intern (format "yas//direct-%s" mode))))
-        (set-default name nil)
-        (set (make-local-variable name) t)))))
+    (dolist (mode (yas/extra-modes))
+      (push mode modes-to-activate))
+    (remove-duplicates
+     (append modes-to-activate
+             (mapcan #'(lambda (mode)
+                         (yas/all-parents mode))
+                     modes-to-activate)))))
 
 (defvar yas/minor-mode-hook nil
   "Hook run when yas/minor-mode is turned on")
@@ -755,7 +778,7 @@ all defined direct keybindings to the command
 (define-minor-mode yas/minor-mode
   "Toggle YASnippet mode.
 
-When YASnippet mode is enabled, the `tas/trigger-key' key expands
+When YASnippet mode is enabled, the `yas/trigger-key' key expands
 snippets of code depending on the mode.
 
 With no argument, this command toggles the mode.
@@ -774,59 +797,68 @@ Key bindings:
          ;; Reload the trigger key
          ;;
          (yas/trigger-key-reload)
-         ;; Load all snippets definitions unless we still don't have a
-         ;; root-directory or some snippets have already been loaded.
-         ;;
-         (unless (or (null yas/snippet-dirs)
-                     (> (hash-table-count yas/tables) 0))
-           (yas/reload-all))
          ;; Install the direct keymaps in `emulation-mode-map-alists'
          ;; (we use `add-hook' even though it's not technically a hook,
          ;; but it works). Then define variables named after modes to
          ;; index `yas/direct-keymaps'.
          ;;
+         ;; Also install the post-command-hook.
+         ;;
          (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
-         (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
+         (add-hook 'post-command-hook 'yas/post-command-handler nil t)
+         ;; Set the `yas//direct-%s' vars for direct keymap expansion
+         ;;
+         (dolist (mode (yas/modes-to-activate))
+           (let ((name (intern (format "yas//direct-%s" mode))))
+             (set-default name nil)
+             (set (make-local-variable name) t)))
+         ;; Perform JIT loads
+         ;;
+         (yas/load-pending-jits))
         (t
-         ;; Uninstall the direct keymaps.
+         ;; Uninstall the direct keymaps and the post-command hook
          ;;
+         (remove-hook 'post-command-hook 'yas/post-command-handler t)
          (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
 
-(defun yas/direct-keymaps-set-vars-runonce ()
-  (yas/direct-keymaps-set-vars)
-  (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
 
-(defvar yas/dont-activate #'(lambda ()
-                              (and yas/snippet-dirs
-                                   (null (yas/get-snippet-tables))))
+(defvar yas/dont-activate nil
   "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
 
 `yas/minor-mode-on' is usually called by `yas/global-mode' so
 this effectively lets you define exceptions to the \"global\"
-behaviour.")
+behaviour. Can also be a function of zero arguments.")
 (make-variable-buffer-local 'yas/dont-activate)
 
 (defun yas/minor-mode-on ()
   "Turn on YASnippet minor mode.
 
-Do this unless `yas/dont-activate' is t or the function
-`yas/get-snippet-tables' (which see), returns an empty list."
+Do this unless `yas/dont-activate' is truish "
   (interactive)
-  (unless (or (and (functionp yas/dont-activate)
-                   (funcall yas/dont-activate))
-              (and (not (functionp yas/dont-activate))
-                   yas/dont-activate))
+  (unless (or (minibufferp)
+              (if (functionp yas/dont-activate)
+                  (funcall yas/dont-activate)
+                yas/dont-activate))
+    ;; Load all snippets definitions unless we still don't have a
+    ;; root-directory or some snippets have already been loaded.
+    ;;
     (yas/minor-mode 1)))
 
-(defun yas/minor-mode-off ()
-  "Turn off YASnippet minor mode."
-  (interactive)
-  (yas/minor-mode -1))
-
+;;;###autoload
 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
   :group 'yasnippet
   :require 'yasnippet)
 
+(defadvice yas/global-mode (before yas/reload-with-jit (arg) activate)
+  (cond ((and arg
+              (numberp arg)
+              (> arg 1))
+         ;; explicitly enabling
+         (yas/reload-all))
+        ((not yas/global-mode)
+         ;; toggling
+         (yas/reload-all))))
+
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Major mode stuff
 ;;
@@ -869,10 +901,10 @@ Do this unless `yas/dont-activate' is t or the function
 
 (define-derived-mode snippet-mode text-mode "Snippet"
   "A mode for editing yasnippets"
-  (set-syntax-table (standard-syntax-table))
   (setq font-lock-defaults '(yas/font-lock-keywords))
   (set (make-local-variable 'require-final-newline) nil)
-  (use-local-map snippet-mode-map))
+  (set (make-local-variable 'comment-start) "#")
+  (set (make-local-variable 'comment-start-skip) "#+[\t ]*"))
 
 
 \f
@@ -880,7 +912,6 @@ Do this unless `yas/dont-activate' is t or the function
 
 (defstruct (yas/template (:constructor yas/make-blank-template))
   "A template for a snippet."
-  table
   key
   content
   name
@@ -889,8 +920,11 @@ Do this unless `yas/dont-activate' is t or the function
   file
   keybinding
   uuid
-  menu-binding-pair)
-
+  menu-binding-pair
+  group      ;; as dictated by the #group: directive or .yas-make-groups
+  perm-group ;; as dictated by `yas/define-menu'
+  table
+  )
 
 (defun yas/populate-template (template &rest args)
   "Helper function to populate a template with properties"
@@ -912,21 +946,15 @@ Has the following fields:
 
   A symbol name normally corresponding to a major mode, but can
   also be a pseudo major-mode to be referenced in
-  `yas/mode-symbol', for example.
+  `yas/extra-modes', for example.
 
 `yas/table-hash'
 
-  A hash table, known as the \"keyhash\" where key is a string or
-  a vector. In case of a string its the snippet trigger key,
-  whereas a vector means it's a direct keybinding. The value is
-  yet another hash of (NAME . TEMPLATE), known as the
-  \"namehash\", where NAME is the snippet name and TEMPLATE is a
-  `yas/template' object.
-
-`yas/table-parents'
-
-  A list of tables considered parents of this table: i.e. when
-  searching for expansions they are searched as well.
+  A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
+  a string or a vector, where the former is the snippet's trigger
+  and the latter means it's a direct keybinding. NAMEHASH is yet
+  another hash of (NAME . TEMPLATE) where NAME is the snippet's
+  name and TEMPLATE is a `yas/template' object.
 
 `yas/table-direct-keymap'
 
@@ -989,7 +1017,6 @@ Has the following fields:
         ;;
         (remhash uuid (yas/table-uuidhash table))))))
 
-
 (defun yas/add-template (table template)
   "Store in TABLE the snippet template TEMPLATE.
 
@@ -998,7 +1025,7 @@ keybinding)."
   (let ((name (yas/template-name template))
         (key (yas/template-key template))
         (keybinding (yas/template-keybinding template))
-        (menu-binding (car (yas/template-menu-binding-pair template))))
+        (menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
     (dolist (k (remove nil (list key keybinding)))
       (puthash name
                template
@@ -1010,20 +1037,57 @@ keybinding)."
       (when (vectorp k)
         (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
 
-    (when menu-binding
-      (setf (getf (cdr menu-binding) :keys)
-            (or (and keybinding (key-description keybinding))
-                (and key (concat key yas/trigger-symbol))))
-      (setcar (cdr menu-binding)
-              name))
+    ;; Update trigger & keybinding in the menu-binding pair
+    ;;
+    (setf (getf (cdr (car menu-binding-pair)) :keys)
+          (or (and keybinding (key-description keybinding))
+              (and key (concat key yas/trigger-symbol))))
 
     (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
 
-(defun yas/update-template (snippet-table template)
-  "Add or update TEMPLATE in SNIPPET-TABLE"
+(defun yas/update-template (table template)
+  "Add or update TEMPLATE in TABLE.
+
+Also takes care of adding and updating to the associated menu."
+  ;; Remove from table by uuid
+  ;;
+  (yas/remove-template-by-uuid table (yas/template-uuid template))
+  ;; Add to table again
+  ;;
+  (yas/add-template table template)
+  ;; Take care of the menu
+  ;;
+  (let ((keymap (yas/menu-keymap-get-create table))
+        (group (yas/template-group template)))
+    (when (and yas/use-menu
+               keymap
+               (not (cdr (yas/template-menu-binding-pair template))))
+      ;; Remove from menu keymap
+      ;;
+      (yas/delete-from-keymap keymap (yas/template-uuid template))
+
+      ;; Add necessary subgroups as necessary.
+      ;;
+      (dolist (subgroup group)
+        (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
+          (unless (and subgroup-keymap
+                       (keymapp subgroup-keymap))
+            (setq subgroup-keymap (make-sparse-keymap))
+            (define-key keymap (vector (make-symbol subgroup))
+              `(menu-item ,subgroup ,subgroup-keymap)))
+            (setq keymap subgroup-keymap)))
+
+      ;; Add this entry to the keymap
+      ;;
+      (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
+        (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
 
-  (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
-  (yas/add-template snippet-table template))
+(defun yas/namehash-templates-alist (namehash)
+  (let (alist)
+    (maphash #'(lambda (k v)
+                 (push (cons k v) alist))
+             namehash)
+    alist))
 
 (defun yas/fetch (table key)
   "Fetch templates in TABLE by KEY.
@@ -1033,12 +1097,7 @@ string and TEMPLATE is a `yas/template' structure."
   (let* ((keyhash (yas/table-hash table))
          (namehash (and keyhash (gethash key keyhash))))
     (when namehash
-      (yas/filter-templates-by-condition
-       (let (alist)
-         (maphash #'(lambda (k v)
-                      (push (cons k v) alist))
-                  namehash)
-         alist)))))
+      (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash)))))
 
 \f
 ;;; Filtering/condition logic
@@ -1050,8 +1109,7 @@ string and TEMPLATE is a `yas/template' structure."
           (save-match-data
             (eval condition))))
     (error (progn
-             (message (format "[yas] error in condition evaluation: %s"
-                              (error-message-string err)))
+             (yas/message 1 "Error in condition evaluation: %s" (error-message-string err))
              nil))))
 
 
@@ -1096,12 +1154,11 @@ conditions to filter out potential expansions."
           (t
            (eq requirement result)))))
 
-(defun yas/table-get-all-parents (table)
-  "Returns a list of all parent tables of TABLE"
-  (let ((parents (yas/table-parents table)))
-    (when parents
-      (append (copy-list parents)
-              (mapcan #'yas/table-get-all-parents parents)))))
+(defun yas/all-parents (mode)
+  "Returns a list of all parent modes of MODE"
+  (let ((parents (gethash mode yas/parents)))
+    (append parents
+            (mapcan #'yas/all-parents parents))))
 
 (defun yas/table-templates (table)
   (when table
@@ -1143,8 +1200,8 @@ the template of a snippet in the current snippet-table."
 (defun yas/table-all-keys (table)
   (when table
     (let ((acc))
-      (maphash #'(lambda (key templates)
-                   (when (yas/filter-templates-by-condition templates)
+      (maphash #'(lambda (key namehash)
+                   (when (yas/filter-templates-by-condition (yas/namehash-templates-alist namehash))
                      (push key acc)))
                (yas/table-hash table))
       acc)))
@@ -1173,8 +1230,8 @@ a list of modes like this to help the judgement."
                               (when result
                                 (format "%s" result))))))
                     (error (if yas/good-grace
-                               (format "[yas] elisp error! %s" (error-message-string err))
-                             (error (format "[yas] elisp error: %s"
+                               (yas/format "elisp error! %s" (error-message-string err))
+                             (error (yas/format "elisp error: %s"
                                             (error-message-string err)))))))))
     (when (and (consp retval)
                (eq 'yas/exception (car retval)))
@@ -1185,8 +1242,8 @@ a list of modes like this to help the judgement."
   (condition-case err
       (eval form)
     (error (if yas/good-grace
-               (format "[yas] elisp error! %s" (error-message-string err))
-             (error (format "[yas] elisp error: %s"
+               (yas/format "elisp error! %s" (error-message-string err))
+             (error (yas/format "elisp error: %s"
                             (error-message-string err)))))))
 
 (defun yas/read-lisp (string &optional nil-on-error)
@@ -1197,70 +1254,54 @@ return an expression that when evaluated will issue an error."
   (condition-case err
       (read string)
     (error (and (not nil-on-error)
-                `(error (error-message-string err))))))
+                `(error (error-message-string ,err))))))
 
 (defun yas/read-keybinding (keybinding)
   "Read KEYBINDING as a snippet keybinding, return a vector."
   (when (and keybinding
              (not (string-match "keybinding" keybinding)))
     (condition-case err
-        (let ((keybinding-string (or (and (string-match "\".*\"" keybinding)
-                                          (read keybinding))
-                                     ;; "KEY-DESC" with quotes is deprecated..., but supported
-                                     keybinding)))
-          (read-kbd-macro keybinding-string 'need-vector))
+        (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
+                            (read keybinding))
+                       (read-kbd-macro keybinding 'need-vector))))
+          res)
       (error
-       (message "[yas] warning: keybinding \"%s\" invalid for snippet \"%s\" since %s."
-                keybinding name (error-message-string err))
+       (yas/message 3 "warning: keybinding \"%s\" invalid since %s."
+                keybinding (error-message-string err))
        nil))))
 
-(defvar yas/mode-symbol nil
-  "If non-nil, lookup snippets using this instead of `major-mode'.")
-(make-variable-buffer-local 'yas/mode-symbol)
+(defvar yas/extra-modes nil
+  "If non-nil, also lookup snippets for this/these modes.
 
-(defun yas/table-get-create (mode)
-  "Get the snippet table corresponding to MODE.
+Can be a symbol or a list of symbols.
+
+This variable probably makes more sense as buffer-local, so
+ensure your use `make-local-variable' when you set it.")
+(defun yas/extra-modes ()
+  (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
+(defvaralias 'yas/mode-symbol 'yas/extra-modes)
 
-Optional DIRECTORY gets recorded as the default directory to
-search for snippet files if the retrieved/created table didn't
-already have such a property."
+(defun yas/table-get-create (mode)
+  "Get or create the snippet table corresponding to MODE."
   (let ((table (gethash mode
                         yas/tables)))
     (unless table
       (setq table (yas/make-snippet-table (symbol-name mode)))
       (puthash mode table yas/tables)
-      (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
-            (yas/table-direct-keymap table)))
+      (push (cons (intern (format "yas//direct-%s" mode))
+                  (yas/table-direct-keymap table))
+            yas/direct-keymaps))
     table))
 
-(defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
+(defun yas/get-snippet-tables ()
   "Get snippet tables for current buffer.
 
-Return a list of 'yas/table' objects indexed by mode.
-
-The modes are tried in this order: optional MODE-SYMBOL, then
-`yas/mode-symbol', then `major-mode' then, unless
-DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
-MODE-SYMBOL or `major-mode'.
-
-Guessing is done by looking up the MODE-SYMBOL's
-`derived-mode-parent' property, see also `derived-mode-p'."
-  (let ((mode-tables
-         (mapcar #'(lambda (mode)
-                     (gethash mode yas/tables))
-                 (append (list mode-symbol)
-                         (if (listp yas/mode-symbol)
-                             yas/mode-symbol
-                           (list yas/mode-symbol))
-                         (list major-mode
-                               (and (not dont-search-parents)
-                                    (get (or mode-symbol major-mode)
-                                         'derived-mode-parent))))))
-        (all-tables))
-    (dolist (table (remove nil mode-tables))
-      (push table all-tables)
-      (nconc all-tables (yas/table-get-all-parents table)))
-    (remove-duplicates all-tables)))
+Return a list of `yas/table' objects. The list of modes to
+consider is returned by `yas/modes-to-activate'"
+  (remove nil
+          (mapcar #'(lambda (mode-name)
+                      (gethash mode-name yas/tables))
+                  (yas/modes-to-activate))))
 
 (defun yas/menu-keymap-get-create (table)
   "Get or create the main menu keymap correspondong to MODE.
@@ -1271,20 +1312,16 @@ them in all `yas/menu-table'"
          (menu-keymap (or (gethash mode yas/menu-table)
                           (puthash mode (make-sparse-keymap) yas/menu-table)))
         (parents (yas/table-parents table)))
-    (mapc #'(lambda (parent)
-              (define-key menu-keymap
-                (vector (intern (concat "parent_shit_" (yas/table-name parent))))
-                (list 'menu-item
-                      (concat "parent-table: "
-                              (yas/table-name parent))
-                      (yas/menu-keymap-get-create parent))))
-          parents)
+    (mapc #'yas/menu-keymap-get-create parents)
+    (define-key yas/minor-mode-menu (vector mode)
+        `(menu-item ,(symbol-name mode) ,menu-keymap
+                    :visible (yas/show-menu-p ',mode)))
     menu-keymap))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;; Template-related and snippet loading functions
 
-(defun yas/parse-template (&optional file group)
+(defun yas/parse-template (&optional file)
   "Parse the template in the current buffer.
 
 Optional FILE is the absolute file name of the file being
@@ -1297,41 +1334,32 @@ Return a snippet-definition, i.e. a list
 
  (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
 
-If the buffer contains a line of \"# --\" then the contents
-above this line are ignored. Variables can be set above this
-line through the syntax:
+If the buffer contains a line of \"# --\" then the contents above
+this line are ignored. Directives can set most of these with the syntax:
 
-#name : value
+# directive-name : directive-value
 
-Here's a list of currently recognized variables:
+Here's a list of currently recognized directives:
 
  * type
  * name
  * contributor
  * condition
+ * group
  * key
  * expand-env
  * binding
- * uuid
-
-#name: #include \"...\"
-# --
-#include \"$1\""
-  ;;
-  ;;
+ * uuid"
   (goto-char (point-min))
   (let* ((type 'snippet)
          (name (and file
                     (file-name-nondirectory file)))
-         (key (unless yas/ignore-filenames-as-triggers
-                (and name
-                     (file-name-sans-extension name))))
+         (key nil)
          template
          bound
          condition
-         (group (or group
-                    (and file
-                         (yas/calculate-group file))))
+         (group (and file
+                     (yas/calculate-group file)))
          expand-env
          binding
          uuid)
@@ -1355,7 +1383,7 @@ Here's a list of currently recognized variables:
                  (when (string= "condition" (match-string-no-properties 1))
                    (setq condition (yas/read-lisp (match-string-no-properties 2))))
                  (when (string= "group" (match-string-no-properties 1))
-                   (message "[yas] Warning: the \"# group:\" is no longer supported!"))
+                   (setq group (match-string-no-properties 2)))
                  (when (string= "expand-env" (match-string-no-properties 1))
                    (setq expand-env (yas/read-lisp (match-string-no-properties 2)
                                                    'nil-on-error)))
@@ -1363,8 +1391,12 @@ Here's a list of currently recognized variables:
                    (setq binding (match-string-no-properties 2)))))
       (setq template
             (buffer-substring-no-properties (point-min) (point-max))))
+    (unless (or key binding)
+      (setq key (and file (file-name-nondirectory file))))
     (when (eq type 'command)
       (setq template (yas/read-lisp (concat "(progn" template ")"))))
+    (when group
+      (setq group (split-string group "\\.")))
     (list key template name condition group expand-env file binding uuid)))
 
 (defun yas/calculate-group (file)
@@ -1384,8 +1416,8 @@ Here's a list of currently recognized variables:
                                                (directory-file-name extra-dir)))))
     group))
 
-(defun yas/subdirs (directory &optional file?)
-  "Return subdirs or files of DIRECTORY according to FILE?."
+(defun yas/subdirs (directory &optional filep)
+  "Return subdirs or files of DIRECTORY according to FILEP."
   (remove-if (lambda (file)
                (or (string-match "^\\."
                                  (file-name-nondirectory file))
@@ -1393,7 +1425,7 @@ Here's a list of currently recognized variables:
                                  (file-name-nondirectory file))
                    (string-match "~$"
                                  (file-name-nondirectory file))
-                   (if file?
+                   (if filep
                        (file-directory-p file)
                      (not (file-directory-p file)))))
              (directory-files directory t)))
@@ -1409,26 +1441,37 @@ Here's a list of currently recognized variables:
     (when yas/current-template
       (if yas/visit-from-menu
           (yas/visit-snippet-file-1 yas/current-template)
-        (let ((where (if mark-active
+        (let ((where (if (region-active-p)
                          (cons (region-beginning) (region-end))
                        (cons (point) (point)))))
           (yas/expand-snippet (yas/template-content yas/current-template)
                               (car where)
-                              (cdr where)))))))
+                              (cdr where)
+                              (yas/template-expand-env yas/current-template)))))))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Popping up for keys and templates
 ;;
+(defvar yas/x-pretty-prompt-templates nil
+  "If non-nil, attempt to prompt for templates like TextMate.")
+
+
 (defun yas/prompt-for-template (templates &optional prompt)
   "Interactively choose a template from the list TEMPLATES.
 
 TEMPLATES is a list of `yas/template'."
   (when templates
-    (some #'(lambda (fn)
-              (funcall fn (or prompt "Choose a snippet: ")
-                       templates
-                       #'yas/template-name))
-          yas/prompt-functions)))
+    (setq templates
+          (sort templates #'(lambda (t1 t2)
+                              (< (length (yas/template-name t1))
+                                 (length (yas/template-name t2))))))
+    (if yas/x-pretty-prompt-templates
+        (yas/x-pretty-prompt-templates "Choose a snippet" templates)
+      (some #'(lambda (fn)
+                (funcall fn (or prompt "Choose a snippet: ")
+                         templates
+                         #'yas/template-name))
+            yas/prompt-functions))))
 
 (defun yas/prompt-for-keys (keys &optional prompt)
   "Interactively choose a template key from the list KEYS."
@@ -1456,59 +1499,58 @@ TEMPLATES is a list of `yas/template'."
   ;;
   (when (and window-system choices)
     (let ((chosen
-           (if (yas/template-p (first choices))
-               (yas/x-prompt-pretty-templates prompt choices)
-             (let (menu d) ;; d for display
-               (dolist (c choices)
-                 (setq d (or (and display-fn (funcall display-fn c))
-                             c))
-                 (cond ((stringp d)
-                        (push (cons (concat "   " d) c) menu))
-                       ((listp d)
-                        (push (car d) menu))))
-               (setq menu (list prompt (push "title" menu)))
-               (x-popup-menu (if (fboundp 'posn-at-point)
-                                 (let ((x-y (posn-x-y (posn-at-point (point)))))
-                                   (list (list (+ (car x-y) 10)
-                                               (+ (cdr x-y) 20))
-                                         (selected-window)))
-                               t)
-                             menu)))))
+           (let (menu d) ;; d for display
+             (dolist (c choices)
+               (setq d (or (and display-fn (funcall display-fn c))
+                           c))
+               (cond ((stringp d)
+                      (push (cons (concat "   " d) c) menu))
+                     ((listp d)
+                      (push (car d) menu))))
+             (setq menu (list prompt (push "title" menu)))
+             (x-popup-menu (if (fboundp 'posn-at-point)
+                               (let ((x-y (posn-x-y (posn-at-point (point)))))
+                                 (list (list (+ (car x-y) 10)
+                                             (+ (cdr x-y) 20))
+                                       (selected-window)))
+                             t)
+                           menu))))
       (or chosen
           (keyboard-quit)))))
 
-(defun yas/x-prompt-pretty-templates (prompt templates)
+(defun yas/x-pretty-prompt-templates (prompt templates)
   "Display TEMPLATES, grouping neatly by table name."
-  (let ((props (list))
+  (let ((organized (make-hash-table :test #'equal))
         menu
         more-than-one-table
         prefix)
     (dolist (tl templates)
-      (push tl (getf props (intern (yas/table-name (yas/template-table tl))))))
-    (setq more-than-one-table (> (length props) 2))
+      (puthash (yas/template-table tl)
+               (cons tl
+                     (gethash (yas/template-table tl) organized))
+               organized))
+    (setq more-than-one-table (> (hash-table-count organized) 1))
     (setq prefix (if more-than-one-table
                      "   " ""))
-    (dolist (thing props)
-      (cond ((listp thing)
-             (setq menu (nconc (mapcar #'(lambda (tl)
-                                           (cons (concat prefix (yas/template-name tl))
-                                                 tl))
-                                       thing)
-                               menu)))
-            (more-than-one-table
-             (push (symbol-name thing) menu))))
+    (if more-than-one-table
+        (maphash #'(lambda (table templates)
+                     (push (yas/table-name table) menu)
+                     (dolist (tl templates)
+                       (push (cons (concat prefix (yas/template-name tl)) tl) menu))) organized)
+      (setq menu (mapcar #'(lambda (tl) (cons (concat prefix (yas/template-name tl)) tl)) templates)))
+
     (setq menu (nreverse menu))
-    (x-popup-menu (if (fboundp 'posn-at-point)
-                      (let ((x-y (posn-x-y (posn-at-point (point)))))
-                        (list (list (+ (car x-y) 10)
-                                    (+ (cdr x-y) 20))
-                              (selected-window)))
-                    t)
-                  (list prompt (push "title" menu)))))
+    (or (x-popup-menu (if (fboundp 'posn-at-point)
+                          (let ((x-y (posn-x-y (posn-at-point (point)))))
+                            (list (list (+ (car x-y) 10)
+                                        (+ (cdr x-y) 20))
+                                  (selected-window)))
+                        t)
+                      (list prompt (push "title" menu)))
+        (keyboard-quit))))
 
 (defun yas/ido-prompt (prompt choices &optional display-fn)
-  (when (and (featurep 'ido)
-             ido-mode)
+  (when (fboundp 'ido-completing-read)
     (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
 
 (eval-when-compile (require 'dropdown-list nil t))
@@ -1516,17 +1558,19 @@ TEMPLATES is a list of `yas/template'."
   (when (featurep 'dropdown-list)
     (let (formatted-choices
           filtered-choices
-          chosen
-          d)
+          d
+          n)
       (dolist (choice choices)
         (setq d (or (and display-fn (funcall display-fn choice))
                       choice))
         (when (stringp d)
           (push d formatted-choices)
           (push choice filtered-choices)))
-      (setq chosen (and formatted-choices
-                        (nth (dropdown-list formatted-choices)
-                             filtered-choices))))))
+
+      (setq n (and formatted-choices (dropdown-list formatted-choices)))
+      (if n
+          (nth n filtered-choices)
+        (keyboard-quit)))))
 
 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
   (let (formatted-choices
@@ -1557,117 +1601,138 @@ TEMPLATES is a list of `yas/template'."
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Loading snippets from files
 ;;
-(defun yas/load-directory-1 (directory &optional mode-sym parents)
-  "Recursively load snippet templates from DIRECTORY."
+(defun yas/load-yas-setup-file (file)
+  (load file 'noerror))
 
-  ;; Load .yas-setup.el files wherever we find them
-  ;;
-  (let ((file (concat directory "/" ".yas-setup")))
-    (when (or (file-readable-p (concat file ".el"))
-              (file-readable-p (concat file ".elc")))
-      (load file)))
+(defun yas/load-directory (top-level-dir &optional use-jit)
+  "Load snippets in directory hierarchy TOP-LEVEL-DIR.
 
-  ;;
-  ;;
-  (unless (file-exists-p (concat directory "/" ".yas-skip"))
-    (let* ((major-mode-and-parents (if mode-sym
-                                       (cons mode-sym parents)
-                                     (yas/compute-major-mode-and-parents (concat directory
-                                                                                 "/dummy"))))
-           (yas/ignore-filenames-as-triggers
-            (or yas/ignore-filenames-as-triggers
-                (file-exists-p (concat directory "/"
-                                       ".yas-ignore-filenames-as-triggers"))))
-           (snippet-defs nil))
-      ;; load the snippet files
-      ;;
-      (with-temp-buffer
-        (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
-          (when (file-readable-p file)
-            (insert-file-contents file nil nil nil t)
-            (push (yas/parse-template file)
-                  snippet-defs))))
-      (when snippet-defs
-        (yas/define-snippets (car major-mode-and-parents)
-                             snippet-defs
-                             (cdr major-mode-and-parents)))
-      ;; now recurse to a lower level
-      ;;
-      (dolist (subdir (yas/subdirs directory))
-        (yas/load-directory-1 subdir
-                              (car major-mode-and-parents)
-                              (cdr major-mode-and-parents))))))
-
-(defun yas/load-directory (directory)
-  "Load snippet definition from a directory hierarchy.
-
-Below the top-level directory, each directory is a mode
-name.  And under each subdirectory, each file is a definition
-of a snippet.  The file name is the trigger key and the
-content of the file is the template."
+Below TOP-LEVEL-DIR each directory should be a mode name.
+
+Optional USE-JIT use jit-loading of snippets."
   (interactive "DSelect the root directory: ")
-  (unless (file-directory-p directory)
-    (error "Error %s not a directory" directory))
   (unless yas/snippet-dirs
-    (setq yas/snippet-dirs directory))
-  (dolist (dir (yas/subdirs directory))
-    (yas/load-directory-1 dir))
+    (setq yas/snippet-dirs top-level-dir))
+  (dolist (dir (yas/subdirs top-level-dir))
+    (let* ((major-mode-and-parents (yas/compute-major-mode-and-parents
+                                    (concat dir "/dummy")))
+           (mode-sym (car major-mode-and-parents))
+           (parents (cdr major-mode-and-parents)))
+      (yas/define-parents mode-sym parents)
+      (let ((form `(yas/load-directory-1 ,dir
+                                         ',mode-sym
+                                         ',parents)))
+        (if use-jit
+            (yas/schedule-jit mode-sym form)
+            (eval form)))))
   (when (interactive-p)
-    (message "[yas] Loaded snippets from %s." directory)))
+    (yas/message 3 "Loaded snippets from %s." top-level-dir)))
 
-(defun yas/load-snippet-dirs ()
-  "Reload the directories listed in `yas/snippet-dirs' or
-   prompt the user to select one."
-  (if yas/snippet-dirs
-      (if (listp yas/snippet-dirs)
-          (dolist (directory (reverse yas/snippet-dirs))
-            (yas/load-directory directory))
-        (yas/load-directory yas/snippet-dirs))
-    (call-interactively 'yas/load-directory)))
-
-(defun yas/reload-all (&optional reset-root-directory)
-  "Reload all snippets and rebuild the YASnippet menu. "
-  (interactive "P")
-  ;; Turn off global modes and minor modes, save their state though
+(defun yas/load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
+  "Recursively load snippet templates from DIRECTORY."
+  (unless (file-exists-p (concat directory "/" ".yas-skip"))
+    (if (and (not no-compiled-snippets)
+             (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas/verbosity 2)))
+        (yas/message 2 "Loading much faster .yas-compiled-snippets from %s" directory)
+      (yas/load-directory-2 directory mode-sym))))
+
+(defun yas/load-directory-2 (directory mode-sym)
+  ;; Load .yas-setup.el files wherever we find them
   ;;
-  (let ((restore-global-mode (prog1 yas/global-mode
-                               (yas/global-mode -1)))
-        (restore-minor-mode (prog1 yas/minor-mode
-                              (yas/minor-mode -1))))
-    ;; Empty all snippet tables and all menu tables
+  (yas/load-yas-setup-file (expand-file-name ".yas-setup" directory))
+  (let* ((default-directory directory)
+         (snippet-defs nil))
+    ;; load the snippet files
     ;;
-    (setq yas/tables (make-hash-table))
-    (setq yas/menu-table (make-hash-table))
-
-    ;; Init the `yas/minor-mode-map', taking care not to break the
-    ;; menu....
+    (with-temp-buffer
+      (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
+        (when (file-readable-p file)
+          (insert-file-contents file nil nil nil t)
+          (push (yas/parse-template file)
+                snippet-defs))))
+    (when snippet-defs
+      (yas/define-snippets mode-sym
+                           snippet-defs))
+    ;; now recurse to a lower level
     ;;
-    (setf (cdr yas/minor-mode-map)
-          (cdr (yas/init-minor-keymap)))
-
-    (when reset-root-directory
-      (setq yas/snippet-dirs nil))
+    (dolist (subdir (yas/subdirs directory))
+      (yas/load-directory-2 subdir
+                            mode-sym))))
 
-    ;; Reload the directories listed in `yas/snippet-dirs' or prompt
-    ;; the user to select one.
-    ;;
+(defun yas/load-snippet-dirs (&optional nojit)
+  "Reload the directories listed in `yas/snippet-dirs' or
+   prompt the user to select one."
+  (let (errors)
     (if yas/snippet-dirs
-        (if (listp yas/snippet-dirs)
-            (dolist (directory (reverse yas/snippet-dirs))
-              (yas/load-directory directory))
-          (yas/load-directory yas/snippet-dirs))
+        (dolist (directory (reverse (yas/snippet-dirs)))
+          (cond ((file-directory-p directory)
+                 (yas/load-directory directory (not nojit))
+                 (yas/message 3 "Loaded %s" directory))
+                (t
+                 (push (yas/message 0 "Check your `yas/snippet-dirs': %s is not a directory" directory) errors))))
       (call-interactively 'yas/load-directory))
-    ;; Reload the direct keybindings
-    ;;
-    (yas/direct-keymaps-reload)
-    ;; Restore the mode configuration
-    ;;
-    (when restore-minor-mode
-      (yas/minor-mode 1))
-    (when restore-global-mode
-      (yas/global-mode 1))
+    errors))
+
+(defun yas/reload-all (&optional no-jit)
+  "Reload all snippets and rebuild the YASnippet menu.
+
+Behaviour is affected by `yas/no-jit', which see."
+  (interactive "p")
+  (catch 'abort
+    (let ((errors)
+          (snippet-editing-buffers
+           (remove-if-not #'(lambda (buffer)
+                              (with-current-buffer buffer yas/editing-template))
+                          (buffer-list))))
+      ;; Warn if there are buffers visiting snippets, since reloading will break
+      ;; any on-line editing of those buffers.
+      ;;
+      (if snippet-editing-buffers
+          (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload?")
+              (mapcar #'kill-buffer snippet-editing-buffers)
+            (yas/message 1 "Aborted reload...")
+            (throw 'abort nil)))
+
+      ;; Empty all snippet tables, parenting info and all menu tables
+      ;;
+      (setq yas/tables (make-hash-table))
+      (setq yas/parents (make-hash-table))
+      (setq yas/menu-table (make-hash-table))
+
+      ;; Cancel all pending 'yas/scheduled-jit-loads'
+      ;;
+      (setq yas/scheduled-jit-loads (make-hash-table))
+
+      ;; Init the `yas/minor-mode-map', taking care not to break the
+      ;; menu....
+      ;;
+      (setf (cdr yas/minor-mode-map)
+            (cdr (yas/init-minor-keymap)))
+
+      ;; Reload the directories listed in `yas/snippet-dirs' or prompt
+      ;; the user to select one.
+      ;;
+      (setq errors (yas/load-snippet-dirs no-jit))
+      ;; Reload the direct keybindings
+      ;;
+      (yas/direct-keymaps-reload)
+      ;; Reload the trigger-key (shoudn't be needed, but see issue #237)
+      ;;
+      (yas/trigger-key-reload)
+
+      (yas/message 3 "Reloaded everything...%s." (if errors " (some errors, check *Messages*)" "")))))
 
-    (message "[yas] Reloading everything... Done.")))
+(defun yas/load-pending-jits ()
+  (when yas/minor-mode
+    (dolist (mode (yas/modes-to-activate))
+      (let ((forms (gethash mode yas/scheduled-jit-loads)))
+        (dolist (form forms)
+          (yas/message  3 "Loading snippets for %s, just in time: %s!" mode form)
+          (eval form))
+        (remhash mode yas/scheduled-jit-loads)))))
+
+;; (when (<= emacs-major-version 22)
+;;   (add-hook 'after-change-major-mode-hook 'yas/load-pending-jits))
 
 (defun yas/quote-string (string)
   "Escape and quote STRING.
@@ -1679,135 +1744,80 @@ foo\"bar\\! -> \"foo\\\"bar\\\\!\""
                                     t)
           "\""))
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;; Yasnippet Bundle
+;;; Snippet compilation function
 
 (defun yas/initialize ()
   "For backward compatibility, enable `yas/minor-mode' globally"
   (yas/global-mode 1))
 
-(defun yas/compile-bundle
-  (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
-  "Compile snippets in SNIPPET-ROOTS to a single bundle file.
-
-YASNIPPET is the yasnippet.el file path.
+(defun yas/compile-directory (top-level-dir)
+  "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
+
+This works by stubbing a few functions, then calling
+`yas/load-directory'."
+  (interactive "DTop level snippet directory?")
+  (flet ((yas/load-yas-setup-file
+          (file)
+          (let ((elfile (concat file ".el")))
+            (when (file-exists-p elfile)
+              (insert ";;; .yas-setup.el support file if any:\n;;;\n")
+              (insert-file-contents elfile)
+              (end-of-buffer)
+              )))
+         (yas/define-snippets
+          (mode snippets)
+          (insert ";;; Snippet definitions:\n;;;\n")
+          (let ((literal-snippets (list))
+                (print-length nil))
+            (dolist (snippet snippets)
+              (let ((key                    (first   snippet))
+                    (template-content       (second  snippet))
+                    (name                   (third   snippet))
+                    (condition              (fourth  snippet))
+                    (group                  (fifth   snippet))
+                    (expand-env             (sixth   snippet))
+                    (file                   nil) ;; (seventh snippet)) ;; omit on purpose
+                    (binding                (eighth  snippet))
+                    (uuid                    (ninth   snippet)))
+                (push `(,key
+                        ,template-content
+                        ,name
+                        ,condition
+                        ,group
+                        ,expand-env
+                        ,file
+                        ,binding
+                        ,uuid)
+                      literal-snippets)))
+            (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets)))
+            (insert "\n\n")))
+         (yas/load-directory-1
+          (dir mode parents &rest ignore)
+          (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
+            (with-temp-file output-file
+              (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
+              (yas/load-directory-2 dir mode)
+              (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
+    (yas/load-directory top-level-dir nil)))
+
+(defun yas/recompile-all ()
+  "Compile every dir in `yas/snippet-dirs'."
+  (interactive)
+  (mapc #'yas/compile-directory (yas/snippet-dirs)))
 
-YASNIPPET-BUNDLE is the output file of the compile result.
 
-SNIPPET-ROOTS is a list of root directories that contains the
-snippets definition.
+;;; JIT loading
+;;;
 
-CODE is the code to be placed at the end of the generated file
-and that can initialize the YASnippet bundle.
+(defvar yas/scheduled-jit-loads (make-hash-table)
+  "Alist of mode-symbols to forms to be evaled when `yas/minor-mode' kicks in.")
 
-Last optional argument DROPDOWN is the filename of the
-dropdown-list.el library.
+(defun yas/schedule-jit (mode form)
+  (puthash mode
+           (cons form
+                 (gethash mode yas/scheduled-jit-loads))
+           yas/scheduled-jit-loads))
 
-Here's the default value for all the parameters:
-
-  (yas/compile-bundle \"yasnippet.el\"
-                      \"yasnippet-bundle.el\"
-                      \"snippets\")
-                      \"(yas/initialize-bundle)
-                        ### autoload
-                        (require 'yasnippet-bundle)`\"
-                      \"dropdown-list.el\")
-"
-  (interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "
-                       "\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))
-
-  (let* ((yasnippet (or yasnippet
-                        "yasnippet.el"))
-         (yasnippet-bundle (or yasnippet-bundle
-                               "./yasnippet-bundle.el"))
-         (snippet-roots (or snippet-roots
-                            "snippets"))
-         (dropdown (or dropdown
-                       "dropdown-list.el"))
-         (code (or (and code
-                        (condition-case err (read code) (error nil))
-                        code)
-                   (concat "(yas/initialize-bundle)"
-                           "\n;;;###autoload" ; break through so that won't
-                           "(require 'yasnippet-bundle)")))
-         (dirs (or (and (listp snippet-roots) snippet-roots)
-                   (list snippet-roots)))
-         (bundle-buffer nil))
-    (with-temp-file yasnippet-bundle
-      (insert ";;; yasnippet-bundle.el --- "
-              "Yet another snippet extension (Auto compiled bundle)\n")
-      (insert-file-contents yasnippet)
-      (goto-char (point-max))
-      (insert "\n")
-      (when dropdown
-        (insert-file-contents dropdown))
-      (goto-char (point-max))
-      (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
-      (insert ";;;;      Auto-generated code         ;;;;\n")
-      (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
-      (insert "(defun yas/initialize-bundle ()\n"
-              "  \"Initialize YASnippet and load snippets in the bundle.\"")
-      (flet ((yas/define-snippets
-              (mode snippets &optional parent-or-parents)
-              (insert ";;; snippets for " (symbol-name mode) "\n")
-              (let ((literal-snippets (list)))
-                (dolist (snippet snippets)
-                  (let ((key                    (first   snippet))
-                        (template-content       (second  snippet))
-                        (name                   (third   snippet))
-                        (condition              (fourth  snippet))
-                        (group                  (fifth   snippet))
-                        (expand-env             (sixth   snippet))
-                        (file                   nil) ;; (seventh snippet)) ;; omit on purpose
-                        (binding                (eighth  snippet))
-                        (uuid                    (ninth   snippet)))
-                    (push `(,key
-                            ,template-content
-                            ,name
-                            ,condition
-                            ,group
-                            ,expand-env
-                            ,file
-                            ,binding
-                            ,uuid)
-                          literal-snippets)))
-                (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
-                (insert "\n\n"))))
-        (dolist (dir dirs)
-          (dolist (subdir (yas/subdirs dir))
-            (let ((file (concat subdir "/.yas-setup.el")))
-              (when (file-readable-p file)
-                (insert ";; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")
-                (goto-char (+ (point)
-                              (second (insert-file-contents file))))))
-            (yas/load-directory-1 subdir nil))))
-
-      (insert (pp-to-string `(yas/global-mode 1)))
-      (insert ")\n\n" code "\n")
-
-      ;; bundle-specific provide and value for yas/dont-activate
-      (let ((bundle-feature-name (file-name-nondirectory
-                                  (file-name-sans-extension
-                                   yasnippet-bundle))))
-        (insert (pp-to-string `(set-default 'yas/dont-activate
-                                            #'(lambda ()
-                                                (and (or yas/snippet-dirs
-                                                         (featurep ',(make-symbol bundle-feature-name)))
-                                                     (null (yas/get-snippet-tables)))))))
-        (insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))
-
-      (insert ";;; "
-              (file-name-nondirectory yasnippet-bundle)
-              " ends here\n"))))
-
-(defun yas/compile-textmate-bundle ()
-  (interactive)
-  (yas/compile-bundle "yasnippet.el"
-                      "./yasnippet-textmate-bundle.el"
-                      "extras/imported/"
-                      (concat "(yas/initialize-bundle)"
-                              "\n;;;###autoload" ; break through so that won't
-                              "(require 'yasnippet-textmate-bundle)")
-                      "dropdown-list.el"))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;;; Some user level functions
@@ -1819,7 +1829,14 @@ Here's the default value for all the parameters:
                    yas/version
                    ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
 
-(defun yas/define-snippets (mode snippets &optional parent-mode)
+(defun yas/define-parents (mode parents)
+  "Add PARENTS to the list of MODE's parents"
+  (puthash mode-sym (remove-duplicates
+                     (append parents
+                             (gethash mode-sym yas/parents)))
+           yas/parents))
+
+(defun yas/define-snippets (mode snippets)
   "Define SNIPPETS for MODE.
 
 SNIPPETS is a list of snippet definitions, each taking the
@@ -1845,54 +1862,21 @@ UUID is the snippets \"unique-id\". Loading a second snippet file
 with the same uuid replaced the previous snippet.
 
 You can use `yas/parse-template' to return such lists based on
-the current buffers contents.
-
-Optional PARENT-MODE can be used to specify the parent tables of
-MODE. It can be a mode symbol of a list of mode symbols. It does
-not need to be a real mode."
-  ;; X) `snippet-table' is created or retrieved for MODE, same goes
-  ;;    for the list of snippet tables `parent-tables'.
-  ;;
+the current buffers contents."
   (let ((snippet-table (yas/table-get-create mode))
-        (parent-tables (mapcar #'yas/table-get-create
-                               (if (listp parent-mode)
-                                   parent-mode
-                                 (list parent-mode))))
-        (menu-keymap nil))
-    ;; X) Connect `snippet-table' with `parent-tables'.
-    ;;
-    ;; TODO: this should be a remove-duplicates of the concatenation
-    ;; of `snippet-table's existings parents with the new parents...
-    ;;
-    (dolist (parent parent-tables)
-      (unless (find parent (yas/table-parents snippet-table))
-        (push parent
-              (yas/table-parents snippet-table))))
-
-    ;; X) The keymap created here here is the menu keymap, it is also
-    ;;    gotten/created according to MODE.  Make a menu entry for
-    ;;    mode
-    ;;
-    (when yas/use-menu
-      (setq menu-keymap (yas/menu-keymap-get-create snippet-table))
-      (define-key yas/minor-mode-menu (vector mode)
-        `(menu-item ,(symbol-name mode) ,menu-keymap
-                    :visible (yas/show-menu-p ',mode))))
-    ;; X) Now, iterate for evey snippet def list
-    ;;
+        (template nil))
     (dolist (snippet snippets)
-      (yas/define-snippets-1 mode snippet snippet-table menu-keymap))))
+      (setq template (yas/define-snippets-1 snippet
+                                            snippet-table)))
+    template))
 
-(defun yas/define-snippets-1 (mode snippet snippet-table menu-keymap)
+(defun yas/define-snippets-1 (snippet snippet-table)
   "Helper for `yas/define-snippets'."
   ;; X) Calculate some more defaults on the values returned by
   ;; `yas/parse-template'.
   ;;
   (let* ((file (seventh snippet))
-         (key (or (car snippet)
-                  (unless yas/ignore-filenames-as-triggers
-                    (and file
-                         (file-name-sans-extension (file-name-nondirectory file))))))
+         (key (car snippet))
          (name (or (third snippet)
                    (and file
                         (file-name-directory file))))
@@ -1903,7 +1887,6 @@ not need to be a real mode."
                   name))
          (template (or (gethash uuid (yas/table-uuidhash snippet-table))
                        (yas/make-blank-template))))
-
     ;; X) populate the template object
     ;;
     (yas/populate-template template
@@ -1911,46 +1894,27 @@ not need to be a real mode."
                            :key         key
                            :content     (second snippet)
                            :name        (or name key)
+                           :group       group
                            :condition   condition
                            :expand-env  (sixth snippet)
                            :file        (seventh snippet)
                            :keybinding  keybinding
                            :uuid         uuid)
-    ;; X) setup the menu groups, reorganizing from group to group if
-    ;;    necessary
-    ;;
-    (when (and yas/use-menu
-               (not (cdr (yas/template-menu-binding-pair template))))
-      (let ((group-keymap menu-keymap))
-        ;; Delete this entry from another group if already exists
-        ;; in some other group. An entry is considered as existing
-        ;; in another group if its name string-matches.
-        ;;
-        (yas/delete-from-keymap group-keymap name)
-
-        ;; ... then add this entry to the correct group
-        (when (and (not (null group))
-                   (not (string= "" group)))
-          (dolist (subgroup (mapcar #'make-symbol
-                                    (split-string group "\\.")))
-            (let ((subgroup-keymap (lookup-key group-keymap
-                                               (vector subgroup))))
-              (when (null subgroup-keymap)
-                (setq subgroup-keymap (make-sparse-keymap))
-                (define-key group-keymap (vector subgroup)
-                  `(menu-item ,(symbol-name subgroup)
-                              ,subgroup-keymap)))
-              (setq group-keymap subgroup-keymap))))
-        (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
-          (define-key group-keymap (vector (gensym)) (car menu-binding-pair)))))
     ;; X) Update this template in the appropriate table. This step
     ;;    also will take care of adding the key indicators in the
     ;;    templates menu entry, if any
     ;;
-    (yas/update-template snippet-table template)))
+    (yas/update-template snippet-table template)
+    ;; X) Return the template
+    ;;
+    ;;
+    template))
 
 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
-  "Get TEMPLATE's menu binding or assign it a new one."
+  "Get TEMPLATE's menu binding or assign it a new one.
+
+TYPE may be `:stay', signalling this menu binding should be
+static in the menu."
   (or (yas/template-menu-binding-pair template)
       (let ((key (yas/template-key template))
             (keybinding (yas/template-keybinding template)))
@@ -1972,42 +1936,49 @@ not need to be a real mode."
         (t
          t)))
 
-(defun yas/delete-from-keymap (keymap name)
-  "Recursively delete items named NAME from KEYMAP and its submenus.
+(defun yas/delete-from-keymap (keymap uuid)
+  "Recursively delete items with UUID from KEYMAP and its submenus."
 
-Skip any submenus named \"parent mode\""
+  ;; XXX: This used to skip any submenus named \"parent mode\"
+  ;;
   ;; First of all, recursively enter submenus, i.e. the tree is
   ;; searched depth first so that stale submenus can be found in the
   ;; higher passes.
   ;;
   (mapc #'(lambda (item)
-            (when (and (keymapp (fourth item))
-                       (stringp (third item))
-                       (not (string-match "parent mode" (third item))))
-              (yas/delete-from-keymap (fourth item) name)))
+            (when (and (listp (cdr item))
+                       (keymapp (third (cdr item))))
+              (yas/delete-from-keymap (third (cdr item)) uuid)))
         (rest keymap))
+  ;; Set the uuid entry to nil
   ;;
-  (when (keymapp keymap)
-    (let ((pos-in-keymap))
-      (while (setq pos-in-keymap
-                   (position-if #'(lambda (item)
-                                    (and (listp item)
-                                         (or
-                                          ;; the menu item we want to delete
-                                          (and (eq 'menu-item (second item))
-                                               (third item)
-                                               (and (string= (third item) name)))
-                                          ;; a stale subgroup
-                                          (and (keymapp (fourth item))
-                                               (not (and (stringp (third item))
-                                                         (string-match "parent mode"
-                                                                       (third item))))
-                                               (null (rest (fourth item)))))))
-                                keymap))
-        (setf (nthcdr pos-in-keymap keymap)
-              (nthcdr (+ 1 pos-in-keymap) keymap))))))
+  (define-key keymap (vector (make-symbol uuid)) nil)
+  ;; Destructively modify keymap
+  ;;
+  (setcdr keymap (delete-if #'(lambda (item)
+                                (or (null (cdr item))
+                                    (and (keymapp (third (cdr item)))
+                                         (null (cdr (third (cdr item)))))))
+                            (rest keymap))))
 
 (defun yas/define-menu (mode menu omit-items)
+  "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
+
+MENU is a list, its elements can be:
+
+- (yas/item UUID) : Creates an entry the snippet identified with
+  UUID. The menu entry for a snippet thus identified is
+  permanent, i.e. it will never move (be reordered) in the menu.
+
+- (yas/separator) : Creates a separator
+
+- (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
+  SUBMENU has the same form as MENU. NAME is also added to the
+  list of groups of the snippets defined thereafter.
+
+OMIT-ITEMS is a list of snippet uuid's that will always be
+ommited from MODE's menu, even if they're manually loaded.
+"
   (let* ((table (yas/table-get-create mode))
          (hash (yas/table-uuidhash table)))
     (yas/define-menu-1 table
@@ -2023,7 +1994,7 @@ Skip any submenus named \"parent mode\""
                                                  :uuid uuid))))
         (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
 
-(defun yas/define-menu-1 (table keymap menu uuidhash)
+(defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
   (dolist (e (reverse menu))
     (cond ((eq (first e) 'yas/item)
            (let ((template (or (gethash (second e) uuidhash)
@@ -2031,33 +2002,24 @@ Skip any submenus named \"parent mode\""
                                                                (yas/make-blank-template)
                                                                uuidhash)
                                                       :table table
+                                                      :perm-group group-list
                                                       :uuid (second e)))))
              (define-key keymap (vector (gensym))
-               ;; '(menu-item "shit" 'ding)
                (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
-          ;; ((eq (first e) 'yas/external-item)
-          ;;  (let ((template (some #'(lambda (table)
-          ;;                            (gethash (second e) (yas/table-uuidhash table)))
-          ;;                        (let (all-tables)
-          ;;                          (maphash #'(lambda (k v)
-          ;;                                       (push v all-tables))
-          ;;                                   yas/tables)
-          ;;                          yas/tables))))
-          ;;    (if template
-          ;;        (define-key keymap (vector (gensym))
-          ;;          ;; '(menu-item "shit" 'ding)
-          ;;          (car (yas/snippet-menu-binding-pair-get-create template :stay)))
-          ;;      (message "[yas] external menu item %s not found anywhere!" (second e)))))
           ((eq (first e) 'yas/submenu)
            (let ((subkeymap (make-sparse-keymap)))
-             (define-key keymap (vector (make-symbol (second e)))
+             (define-key keymap (vector (gensym))
                `(menu-item ,(second e) ,subkeymap))
-             (yas/define-menu-1 table subkeymap (third e) uuidhash)))
+             (yas/define-menu-1 table
+                                subkeymap
+                                (third e)
+                                uuidhash
+                                (append group-list (list (second e))))))
           ((eq (first e) 'yas/separator)
            (define-key keymap (vector (gensym))
              '(menu-item "----")))
           (t
-           (message "[yas] don't know anything about menu entry %s" (first e))))))
+           (yas/message 3 "Don't know anything about menu entry %s" (first e))))))
 
 (defun yas/define (mode key template &optional name condition group)
   "Define a snippet.  Expanding KEY into TEMPLATE.
@@ -2119,14 +2081,20 @@ Optional argument FIELD is for non-interactive use and is an
 object satisfying `yas/field-p' to restrict the expansion to."
   (interactive)
   (setq yas/condition-cache-timestamp (current-time))
-  (multiple-value-bind (templates start end) (if field
-                                                 (save-restriction
-                                                   (narrow-to-region (yas/field-start field)
-                                                                     (yas/field-end field))
-                                                   (yas/current-key))
-                                               (yas/current-key))
-    (if templates
-        (yas/expand-or-prompt-for-template templates start end)
+  (let (templates-and-pos)
+    (unless (and yas/expand-only-for-last-commands
+                 (not (member last-command yas/expand-only-for-last-commands)))
+      (setq templates-and-pos (if field
+                                  (save-restriction
+                                    (narrow-to-region (yas/field-start field)
+                                                      (yas/field-end field))
+                                    (yas/current-key))
+                                (yas/current-key))))
+    (if (and templates-and-pos
+             (first templates-and-pos))
+        (yas/expand-or-prompt-for-template (first templates-and-pos)
+                                           (second templates-and-pos)
+                                           (third templates-and-pos))
       (yas/fallback 'trigger-key))))
 
 (defun yas/expand-from-keymap ()
@@ -2135,7 +2103,10 @@ object satisfying `yas/field-p' to restrict the expansion to."
 If expansion fails, execute the previous binding for this key"
   (interactive)
   (setq yas/condition-cache-timestamp (current-time))
-  (let* ((vec (this-command-keys-vector))
+  (let* ((yas/prefix current-prefix-arg)
+         (vec (subseq (this-command-keys-vector) (if current-prefix-arg
+                                                     universal-argument-num-events
+                                                   0)))
          (templates (mapcan #'(lambda (table)
                                 (yas/fetch table vec))
                             (yas/get-snippet-tables))))
@@ -2239,7 +2210,7 @@ by condition."
                                     (or (and (rest templates) ;; more than one template for same key
                                              (yas/prompt-for-template templates))
                                         (car templates))))
-         (where (if mark-active
+         (where (if (region-active-p)
                     (cons (region-beginning) (region-end))
                   (cons (point) (point)))))
     (if yas/current-template
@@ -2247,7 +2218,7 @@ by condition."
                             (car where)
                             (cdr where)
                             (yas/template-expand-env yas/current-template))
-      (message "[yas] No snippets can be inserted here!"))))
+      (yas/message 3 "No snippets can be inserted here!"))))
 
 (defun yas/visit-snippet-file ()
   "Choose a snippet to edit, selection like `yas/insert-snippet'.
@@ -2257,21 +2228,22 @@ visited file in `snippet-mode'."
   (interactive)
   (let* ((yas/buffer-local-condition 'always)
          (templates (yas/all-templates (yas/get-snippet-tables)))
+         (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
          (template (and templates
-                        (or (and (rest templates) ;; more than one template for same key
-                                 (yas/prompt-for-template templates
-                                                          "Choose a snippet template to edit: "))
+                        (or (yas/prompt-for-template templates
+                                                     "Choose a snippet template to edit: ")
                             (car templates)))))
 
-    (when template
-      (yas/visit-snippet-file-1 template))))
+    (if template
+        (yas/visit-snippet-file-1 template)
+      (message "No snippets tables active!"))))
 
 (defun yas/visit-snippet-file-1 (template)
   (let ((file (yas/template-file template)))
     (cond ((and file (file-readable-p file))
            (find-file-other-window file)
            (snippet-mode)
-           (setq yas/editing-template template))
+           (set (make-local-variable 'yas/editing-template) template))
           (file
            (message "Original file %s no longer exists!" file))
           (t
@@ -2293,7 +2265,7 @@ visited file in `snippet-mode'."
                          (pp-to-string (yas/template-content template))
                        (yas/template-content template))))
            (snippet-mode)
-           (setq yas/editing-template template)))))
+           (set (make-local-variable 'yas/editing-template) template)))))
 
 (defun yas/guess-snippet-directories-1 (table)
   "Guesses possible snippet subdirectories for TABLE."
@@ -2307,27 +2279,21 @@ visited file in `snippet-mode'."
   "Try to guess suitable directories based on the current active
 tables (or optional TABLE).
 
-Returns a a list of options alist TABLE -> DIRS where DIRS are
-all the possibly directories where snippets of table might be
-lurking."
+Returns a list of elemts (TABLE . DIRS) where TABLE is a
+`yas/table' object and DIRS is a list of all possible directories
+where snippets of table might exist."
   (let ((main-dir (replace-regexp-in-string
                    "/+$" ""
-                   (or (and (listp yas/snippet-dirs)
-                            (first yas/snippet-dirs))
-                       yas/snippet-dirs
-                       (setq yas/snippet-dirs "~/.emacs.d/snippets"))))
+                   (or (first (or (yas/snippet-dirs)
+                                  (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
         (tables (or (and table
                          (list table))
                     (yas/get-snippet-tables))))
-    ;; HACK! the snippet table created here is a dummy table that
-    ;; holds the correct name so that `yas/make-directory-maybe' can
-    ;; work. The real table, if it does not exist in
-    ;; yas/tables will be created when the first snippet for
-    ;; that mode is loaded.
+    ;; HACK! the snippet table created here is actually registered!
     ;;
     (unless (or table (gethash major-mode yas/tables))
-      (setq tables (cons (yas/make-snippet-table (symbol-name major-mode))
-                         tables)))
+      (push (yas/table-get-create major-mode)
+            tables))
 
     (mapcar #'(lambda (table)
                 (cons table
@@ -2341,7 +2307,7 @@ lurking."
   (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
       (let ((candidate (first (cdr table-and-dirs))))
         (unless (file-writable-p (file-name-directory candidate))
-          (error "[yas] %s is not writable." candidate))
+          (error (yas/format "%s is not writable." candidate)))
         (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
                               candidate
                               (if (gethash (intern (yas/table-name (car table-and-dirs)))
@@ -2356,21 +2322,23 @@ lurking."
               ;; create the .yas-parents file here...
               candidate)))))
 
-(defun yas/new-snippet (&optional choose-instead-of-guess)
-  ""
+(defun yas/new-snippet (&optional no-template)
+  "Pops a new buffer for writing a snippet.
+
+Expands a snippet-writing snippet, unless the optional prefix arg
+NO-TEMPLATE is non-nil."
   (interactive "P")
   (let ((guessed-directories (yas/guess-snippet-directories)))
 
-    (switch-to-buffer (format "*new snippet for %s*"
-                              (if guessed-directories
-                                  (yas/table-name (car (first guessed-directories)))
-                                "unknown mode")))
+    (switch-to-buffer "*new snippet*")
     (erase-buffer)
+    (kill-all-local-variables)
     (snippet-mode)
-    (setq yas/guessed-directories guessed-directories)
-    (unless (and choose-instead-of-guess
-                 (not (y-or-n-p "Insert a snippet with useful headers? ")))
-      (yas/expand-snippet "\
+    (yas/minor-mode 1)
+    (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
+                                                              (intern (yas/table-name (car d))))
+                                                          guessed-directories))
+    (unless no-template (yas/expand-snippet "\
 # -*- mode: snippet -*-
 # name: $1
 # key: $2${3:
@@ -2381,7 +2349,7 @@ lurking."
 $0"))))
 
 (defun yas/find-snippets (&optional same-window )
-  "Look for user snippets in guessed current mode's directory.
+  "Find snippet file in guessed current mode's directory.
 
 Calls `find-file' interactively in the guessed directory.
 
@@ -2409,9 +2377,7 @@ there, otherwise, proposes to create the first option returned by
                              (rest guessed-directories)))))
     (unless chosen
       (when (y-or-n-p "Having trouble... go to snippet root dir? ")
-        (setq chosen (if (listp yas/snippet-dirs)
-                         (first yas/snippet-dirs)
-                       yas/snippet-dirs))))
+        (setq chosen (first (yas/snippet-dirs)))))
     (if chosen
         (let ((default-directory chosen))
           (setq buffer (call-interactively (if same-window
@@ -2424,18 +2390,25 @@ there, otherwise, proposes to create the first option returned by
                 (snippet-mode)))))
       (message "Could not guess snippet dir!"))))
 
-(defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)
+(defun yas/compute-major-mode-and-parents (file)
+  "Given FILE, find the nearest snippet directory for a given
+mode, then return a list (MODE-SYM PARENTS), the mode's symbol and a list
+representing one or more of the mode's parents.
+
+Note that MODE-SYM need not be the symbol of a real major mode,
+neither do the elements of PARENTS."
   (let* ((file-dir (and file
-                        (directory-file-name (or (locate-dominating-file file ".yas-make-groups")
+                        (directory-file-name (or (some #'(lambda (special)
+                                                           (locate-dominating-file file special))
+                                                       '(".yas-setup.el"
+                                                         ".yas-make-groups"
+                                                         ".yas-parents"))
                                                  (directory-file-name (file-name-directory file))))))
          (parents-file-name (concat file-dir "/.yas-parents"))
          (major-mode-name (and file-dir
                                (file-name-nondirectory file-dir)))
          (major-mode-sym (or (and major-mode-name
-                                  (intern major-mode-name))
-                             (when prompt-if-failed
-                               (read-from-minibuffer
-                                "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
+                                  (intern major-mode-name))))
          (parents (when (file-readable-p parents-file-name)
                          (mapcar #'intern
                                  (split-string
@@ -2452,8 +2425,8 @@ there, otherwise, proposes to create the first option returned by
 (defvar yas/current-template nil
   "Holds the current template being expanded into a snippet.")
 
-(defvar yas/guessed-directories nil
-  "Supporting variable for `yas/load-snippet-buffer' and `yas/new-snippet'")
+(defvar yas/guessed-modes nil
+  "List of guessed modes supporting `yas/load-snippet-buffer'.")
 
 (defun yas/load-snippet-buffer (&optional kill)
   "Parse and load current buffer's snippet definition.
@@ -2461,129 +2434,70 @@ there, otherwise, proposes to create the first option returned by
 With optional prefix argument KILL quit the window and buffer."
   (interactive "P")
   (cond
-   ;; X) Option 1: We have `yas/editing-template', this buffer's
+   ;;  We have `yas/editing-template', this buffer's
    ;;  content comes from a template which is already loaded and
    ;;  neatly positioned,...
    ;;
-   ((and (boundp 'yas/editing-template)
-         yas/editing-template
-         (yas/template-p yas/editing-template))
-
-    (let ((parsed (yas/parse-template (yas/template-file yas/editing-template))))
-      ;; ... just change its template, expand-env, condition, key,
-      ;; keybinding and name. The group cannot be changed.
-      (yas/populate-template yas/editing-template
-                             :content    (second parsed)
-                             :key        (first parsed)
-                             :name       (third parsed)
-                             :condition  (fourth parsed)
-                             :expand-env (sixth parsed)
-                             :keybinding (yas/read-keybinding (eighth parsed)))
-      (yas/update-template (yas/template-table yas/editing-template)
-                          yas/editing-template))
-    ;; Now, prompt for new file creation much like
-    ;; `yas/new-snippet' if one of the following is true:
-    ;;
-    ;; 1) `yas/snippet-dirs' is a list and its first element does not
-    ;; match this template's file (i.e. this is a library snippet, not
-    ;; a user snippet).
-    ;;
-    ;; 2) yas/editing-template comes from a file that we cannot write to...
-    ;;
-    (when (or (and (listp yas/snippet-dirs)
-                   (second yas/snippet-dirs)
-                   (not (string-match (expand-file-name (first yas/snippet-dirs))
-                                      (yas/template-file yas/editing-template))))
-              (and (yas/template-file yas/editing-template)
-                   (not (file-writable-p (yas/template-file yas/editing-template))))
-              (not (yas/template-file yas/editing-template)))
-      (when (y-or-n-p "[yas] Also save snippet buffer to new file? ")
-        (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
-               (chosen (and option
-                            (yas/make-directory-maybe option))))
-          (when chosen
-            (let ((default-file-name (or (and (yas/template-file yas/editing-template)
-                                              (file-name-nondirectory (yas/template-file yas/editing-template)))
-                                         (yas/template-name yas/editing-template))))
-              (write-file (concat chosen "/"
-                                  (read-from-minibuffer (format "File name to create in %s? " chosen)
-                                                        default-file-name)))
-              (setf (yas/template-file yas/editing-template) buffer-file-name))))))
-    (when kill
-      (quit-window kill))
-    (message "[yas] Snippet \"%s\" loaded for %s."
-             (yas/template-name yas/editing-template)
-             (yas/table-name (yas/template-table yas/editing-template))))
-   (;; X) Option 2: We have a file name, consider this a brand new
-    ;; snippet and calculate name, groups, etc from the current
-    ;; file-name and buffer content
-    ;;
-    buffer-file-name
-    (let ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name)))
-      (if major-mode-and-parent
-          (let* ((yas/ignore-filenames-as-triggers (or yas/ignore-filenames-as-triggers
-                                                       (locate-dominating-file buffer-file-name ".yas-ignore-filenames-as-triggers")))
-                 (parsed (yas/parse-template buffer-file-name))
-                 (name (and parsed
-                            (third parsed))))
-            (when name
-              (yas/define-snippets (car major-mode-and-parent)
-                                   (list parsed)
-                                   (cdr major-mode-and-parent)))
-            (when (and (buffer-modified-p)
-                       (y-or-n-p "Also save snippet buffer? "))
-              (save-buffer))
-            (when kill
-              (quit-window kill))
-            (message "[yas] Snippet \"%s\" loaded for %s."
-                     name
-                     (car major-mode-and-parent)))
-        (message (format "[yas] Unknown major mode for snippet at %s" buffer-file-name)))))
-
-   ;; X) Option 3: We have `yas/guessed-directories', this
-   ;;  buffer's content comes from `yas/new-snippet' call. Prompt
-   ;;  user for dir and name in guessed dirs, then call
-   ;;  `yas/load-snippet-buffer' (ourselves) again to load the
-   ;;  snippet based on the file-name.
+   (yas/editing-template
+    (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
+                           (yas/template-table yas/editing-template)))
+   ;; Try to use `yas/guessed-modes'. If we don't have that use the
+   ;; value from `yas/compute-major-mode-and-parents'
    ;;
-   ((and (boundp 'yas/guessed-directories)
-         yas/guessed-directories)
-    (let* ((yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
-           (guessed-directories yas/guessed-directories)
-           (option (or (and (not (y-or-n-p "Let yasnippet guess tables? "))
-                            (first
-                             (yas/guess-snippet-directories
-                              (some #'(lambda (fn)
-                                        (funcall fn "Choose any snippet table: "
-                                                 (let (res)
-                                                   (maphash #'(lambda (k v)
-                                                                (push v res))
-                                                            yas/tables)
-                                                   res)
-                                                 #'yas/table-name))
-                                    yas/prompt-functions))))
-                       (and (second guessed-directories)
-                            (some #'(lambda (fn)
-                                      (funcall fn "Choose from guessed list of tables: "
-                                               guessed-directories
-                                               #'(lambda (option)
-                                                   (yas/table-name (car option)))))
-                                  yas/prompt-functions))
-                       (first guessed-directories)))
-           (chosen))
-      (setq chosen (yas/make-directory-maybe option))
-
-      (unless chosen
-        (when (y-or-n-p "Having trouble... use snippet root dir? ")
-          (setq chosen (if (listp yas/snippet-dirs)
-                           (first yas/snippet-dirs)
-                         yas/snippet-dirs))))
-      (when chosen
-        (let ((default-directory chosen))
-          (call-interactively 'write-file))
-        (setq yas/guessed-directories nil)
-        (setq yas/editing-template nil)
-        (yas/load-snippet-buffer))))))
+   (t
+    (unless yas/guessed-modes
+      (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
+    (let* ((prompt (if (and (featurep 'ido)
+                            ido-mode)
+                       'ido-completing-read 'completing-read))
+           (table (yas/table-get-create
+                   (intern
+                    (funcall prompt (format "Choose or enter a table (yas guesses %s): "
+                                            (if yas/guessed-modes
+                                                (first yas/guessed-modes)
+                                              "nothing"))
+                             (mapcar #'symbol-name yas/guessed-modes)
+                             nil
+                             nil
+                             nil
+                             nil
+                             (if (first yas/guessed-modes)
+                                 (symbol-name (first yas/guessed-modes))))))))
+      (set (make-local-variable 'yas/editing-template)
+           (yas/define-snippets-1 (yas/parse-template buffer-file-name)
+                                  table)))))
+  ;; Now, offer to save this shit iff:
+  ;;
+  ;; 1) `yas/snippet-dirs' is a list and its first element does not
+  ;; match this template's file (i.e. this is a library snippet, not
+  ;; a user snippet) OR
+  ;;
+  ;; 2) yas/editing-template comes from a file that we cannot write to...
+  ;;
+  (when (or (not (yas/template-file yas/editing-template))
+            (not (file-writable-p (yas/template-file yas/editing-template)))
+            (and (listp yas/snippet-dirs)
+                 (second yas/snippet-dirs)
+                 (not (string-match (expand-file-name (first yas/snippet-dirs))
+                                    (yas/template-file yas/editing-template)))))
+
+    (when (y-or-n-p (yas/format "Looks like a library or new snippet. Save to new file? "))
+      (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
+             (chosen (and option
+                          (yas/make-directory-maybe option))))
+        (when chosen
+          (let ((default-file-name (or (and (yas/template-file yas/editing-template)
+                                            (file-name-nondirectory (yas/template-file yas/editing-template)))
+                                       (yas/template-name yas/editing-template))))
+            (write-file (concat chosen "/"
+                                (read-from-minibuffer (format "File name to create in %s? " chosen)
+                                                      default-file-name)))
+            (setf (yas/template-file yas/editing-template) buffer-file-name))))))
+  (when kill
+    (quit-window kill))
+  (yas/message 3 "Snippet \"%s\" loaded for %s."
+           (yas/template-name yas/editing-template)
+           (yas/table-name (yas/template-table yas/editing-template))))
 
 
 (defun yas/tryout-snippet (&optional debug)
@@ -2594,9 +2508,8 @@ With optional prefix argument KILL quit the window and buffer."
          (test-mode (or (and (car major-mode-and-parent)
                              (fboundp (car major-mode-and-parent))
                              (car major-mode-and-parent))
-                        (and yas/guessed-directories
-                             (intern (yas/table-name (car (first yas/guessed-directories)))))
-                        (intern (read-from-minibuffer "[yas] please input a mode: "))))
+                        (first yas/guessed-modes)
+                        (intern (read-from-minibuffer (yas/format "Please input a mode: ")))))
          (yas/current-template
           (and parsed
                (fboundp test-mode)
@@ -2607,20 +2520,25 @@ With optional prefix argument KILL quit the window and buffer."
                                       :name        (third parsed)
                                       :expand-env  (sixth parsed)))))
     (cond (yas/current-template
-           (let ((buffer-name (format "*YAS TEST: %s*" (yas/template-name yas/current-template))))
-             (set-buffer (switch-to-buffer buffer-name))
-             (erase-buffer)
+           (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
+             (kill-buffer (get-buffer-create buffer-name))
+             (switch-to-buffer (get-buffer-create buffer-name))
              (setq buffer-undo-list nil)
              (condition-case nil (funcall test-mode) (error nil))
+             (setq buffer-read-only nil)
              (yas/expand-snippet (yas/template-content yas/current-template)
                                  (point-min)
                                  (point-max)
                                  (yas/template-expand-env yas/current-template))
              (when (and debug
                         (require 'yasnippet-debug nil t))
-               (add-hook 'post-command-hook 'yas/debug-snippet-vars 't 'local))))
+               (add-hook 'post-command-hook 'yas/debug-snippet-vars nil t))))
           (t
-           (message "[yas] Cannot test snippet for unknown major mode")))))
+           (yas/message 3 "Cannot test snippet for unknown major mode")))))
+
+(defun yas/template-fine-group (template)
+  (car (last (or (yas/template-group template)
+                 (yas/template-perm-group template)))))
 
 (defun yas/describe-tables (&optional choose)
   "Display snippets for each table."
@@ -2640,68 +2558,92 @@ With optional prefix argument KILL quit the window and buffer."
          (continue t)
          (yas/condition-cache-timestamp (current-time)))
     (with-current-buffer buffer
-      (let ((buffer-read-only nil))
-        (erase-buffer)
-        (cond ((not by-name-hash)
-               (insert "YASnippet tables by UUID: \n")
-               (while (and table-lists
-                           continue)
-                 (dolist (table (car table-lists))
-                   (insert (format "\nSnippet table `%s'"
-                                   (yas/table-name table)))
-                   (if (yas/table-parents table)
-                       (insert (format " parents: %s\n"
-                                       (mapcar #'yas/table-name
-                                               (yas/table-parents table))))
-                     (insert "\n"))
-                   (let ((always (cons "(a)" (list)))
-                         (active (cons "(y)" (list)))
-                         (sleeping (cons "(n)" (list))))
-                     (maphash #'(lambda (k v)
-                                  (let ((condition (yas/template-condition v)))
-                                    (if condition
-                                      (with-current-buffer original-buffer
-                                        (if (yas/eval-condition condition)
-                                            (push v (cdr active))
-                                          (push v (cdr sleeping))))
-                                      (push v (cdr always)))))
-                              (yas/table-uuidhash table))
-                     (dolist (type-and-templates (list always active sleeping))
-                       (dolist (p (cdr type-and-templates))
-                         (let ((name (yas/template-name p)))
-                           (insert (propertize (format "%s \\\\snippet `%s'" (car type-and-templates) name) 'yasnippet p))
-                           (insert (make-string (max (- 50 (length name))
-                                                     1) ? ))
-                           (when (yas/template-key p)
-                             (insert (format "key \"%s\" " (yas/template-key p))))
-                           (when (yas/template-keybinding p)
-                             (insert (format "bound to %s " (key-description (yas/template-keybinding p)))))
-                           (insert "\n"))))))
-                 (setq table-lists (cdr table-lists))
-                 (when table-lists
-                   (yas/create-snippet-xrefs)
-                   (display-buffer buffer)
-                   (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
-               (yas/create-snippet-xrefs)
-               (help-mode))
-              (t
-               (insert "\n\nYASnippet tables by NAMEHASH: \n")
-               (dolist (table (append active-tables remain-tables))
-                 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
-                 (let ((keys))
-                   (maphash #'(lambda (k v)
-                                (push k keys))
-                            (yas/table-hash table))
-                   (dolist (key keys)
-                     (insert (format "   key %s maps snippets: %s\n" key
-                                     (let ((names))
-                                       (maphash #'(lambda (k v)
-                                                    (push k names))
-                                                (gethash key (yas/table-hash table)))
-                                       names))))))))))
-    (display-buffer buffer)
-    (with-current-buffer buffer
-      (goto-char (point-min)))))
+      (setq buffer-read-only nil)
+      (erase-buffer)
+      (cond ((not by-name-hash)
+             (insert "YASnippet tables: \n")
+             (while (and table-lists
+                         continue)
+               (dolist (table (car table-lists))
+                 (yas/describe-pretty-table table original-buffer))
+               (setq table-lists (cdr table-lists))
+               (when table-lists
+                 (yas/create-snippet-xrefs)
+                 (display-buffer buffer)
+                 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
+             (yas/create-snippet-xrefs)
+             (help-mode)
+             (goto-char 1))
+            (t
+             (insert "\n\nYASnippet tables by NAMEHASH: \n")
+             (dolist (table (append active-tables remain-tables))
+               (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
+               (let ((keys))
+                 (maphash #'(lambda (k v)
+                              (push k keys))
+                          (yas/table-hash table))
+                 (dolist (key keys)
+                   (insert (format "   key %s maps snippets: %s\n" key
+                                   (let ((names))
+                                     (maphash #'(lambda (k v)
+                                                  (push k names))
+                                              (gethash key (yas/table-hash table)))
+                                     names))))))))
+      (goto-char 1)
+      (setq buffer-read-only t))
+    (display-buffer buffer)))
+
+(defun yas/describe-pretty-table (table &optional original-buffer)
+  (insert (format "\nSnippet table `%s'"
+                  (yas/table-name table)))
+  (if (yas/table-parents table)
+      (insert (format " parents: %s\n"
+                      (mapcar #'yas/table-name
+                              (yas/table-parents table))))
+    (insert "\n"))
+  (insert (make-string 100 ?-) "\n")
+  (insert "group                   state name                                    key             binding\n")
+  (let ((groups-hash (make-hash-table :test #'equal)))
+    (maphash #'(lambda (k v)
+                 (let ((group (or (yas/template-fine-group v)
+                                  "(top level)")))
+                   (when (yas/template-name v)
+                     (puthash group
+                              (cons v (gethash group groups-hash))
+                              groups-hash))))
+             (yas/table-uuidhash table))
+    (maphash
+     #'(lambda (group templates)
+         (setq group (truncate-string-to-width group 25 0 ?  "..."))
+         (insert (make-string 100 ?-) "\n")
+         (dolist (p templates)
+           (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
+                                                             'yasnippet p)
+                                                 50 0 ? "..."))
+                 (group (prog1 group
+                          (setq group (make-string (length group) ? ))))
+                 (condition-string (let ((condition (yas/template-condition p)))
+                                     (if (and condition
+                                              original-buffer)
+                                         (with-current-buffer original-buffer
+                                           (if (yas/eval-condition condition)
+                                               "(y)"
+                                             "(s)"))
+                                       "(a)"))))
+             (insert group " ")
+             (insert condition-string " ")
+             (insert name
+                     (if (string-match "\\.\\.\\.$" name)
+                         "'"
+                       " ")
+                     " ")
+             (insert (truncate-string-to-width (or (yas/template-key p) "")
+                                               15 0 ?  "...") " ")
+             (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
+                                               15 0 ?  "...") " ")
+             (insert "\n"))))
+     groups-hash)))
+
 
 \f
 ;;; User convenience functions, for using in snippet definitions
@@ -2752,10 +2694,12 @@ If found, the content of subexp group SUBEXP (default 0) is
 
 Otherwise throw exception."
   (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
-    (yas/throw (format "[yas] field only allows %s" possibilities))))
+    (yas/throw (yas/format "Field only allows %s" possibilities))))
 
 (defun yas/field-value (number)
-  "A primary field transformation..."
+  "Get the string for field with NUMBER.
+
+Use this in primary and mirror transformations to tget."
   (let* ((snippet (car (yas/snippets-at-point)))
          (field (and snippet
                      (yas/snippet-find-field snippet number))))
@@ -2763,10 +2707,17 @@ Otherwise throw exception."
       (yas/field-text-for-display field))))
 
 (defun yas/text ()
+  "Return `yas/text' if that exists and is non-empty, else nil."
   (if (and yas/text
            (not (string= "" yas/text)))
       yas/text))
 
+;; (defun yas/selected-text ()
+;;   "Return `yas/selected-text' if that exists and is non-empty, else nil."
+;;   (if (and yas/selected-text
+;;            (not (string= "" yas/selected-text)))
+;;       yas/selected-text))
+
 (defun yas/get-field-once (number &optional transform-fn)
   (unless yas/modified-p
     (if transform-fn
@@ -2780,11 +2731,13 @@ Otherwise throw exception."
 (defun yas/inside-string ()
   (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
 
-(defun yas/unimplemented ()
+(defun yas/unimplemented (&optional missing-feature)
   (if yas/current-template
-      (if (y-or-n-p "This snippet is unimplemented. Visit the snippet definition? ")
+      (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
+                            (or missing-feature
+                                "something")))
           (yas/visit-snippet-file-1 yas/current-template))
-    (message "No implementation.")))
+    (message "No implementation. Missing %s" (or missing-feature "something"))))
 
 \f
 ;;; Snippet expansion and field management
@@ -2798,9 +2751,6 @@ Otherwise throw exception."
 (defconst yas/prefix nil
   "A prefix argument for expansion direct from keybindings")
 
-(defvar yas/deleted-text nil
-  "The text deleted in the last snippet expansion.")
-
 (defvar yas/selected-text nil
   "The selected region deleted on the last snippet expansion.")
 
@@ -2809,7 +2759,8 @@ Otherwise throw exception."
 
 (make-variable-buffer-local 'yas/active-field-overlay)
 (make-variable-buffer-local 'yas/field-protection-overlays)
-(make-variable-buffer-local 'yas/deleted-text)
+(put 'yas/active-field-overlay 'permanent-local t)
+(put 'yas/field-protection-overlays 'permanent-local t)
 
 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
   "A snippet.
@@ -2846,9 +2797,13 @@ Otherwise throw exception."
   marker
   next)
 
-(defun yas/apply-transform (field-or-mirror field)
-  "Calculate the value of the field/mirror. If there's a transform
-for this field, apply it. Otherwise, returned nil."
+(defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
+  "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
+
+If there is no transform for ht field, return nil.
+
+If there is a transform but it returns nil, return the empty
+string iff EMPTY-ON-NIL-P is true."
   (let* ((yas/text (yas/field-text-for-display field))
          (text yas/text)
          (yas/modified-p (yas/field-modified-p field))
@@ -2863,7 +2818,7 @@ for this field, apply it. Otherwise, returned nil."
                            (save-excursion
                              (goto-char start-point)
                              (let ((ret (yas/eval-lisp transform)))
-                               (or ret ""))))))
+                               (or ret (and empty-on-nil-p "")))))))
     transformed))
 
 (defsubst yas/replace-all (from to &optional text)
@@ -2905,10 +2860,24 @@ have, compare through the field's start point"
 
 (defun yas/field-probably-deleted-p (snippet field)
   "Guess if SNIPPET's FIELD should be skipped."
-  (and (zerop (- (yas/field-start field) (yas/field-end field)))
-       (or (yas/field-parent-field field)
-           (and (eq field (car (last (yas/snippet-fields snippet))))
-                (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))))
+  (and
+   ;; field must be zero lentgh
+   ;;
+   (zerop (- (yas/field-start field) (yas/field-end field)))
+   ;; skip if:
+   (or
+    ;;  1) is a nested field and it's been modified
+    ;;
+    (and (yas/field-parent-field field)
+         (yas/field-modified-p field))
+    ;;  2) ends just before the snippet end
+    ;;
+    (and (eq field (car (last (yas/snippet-fields snippet))))
+         (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
+   ;; the field numbered 0, just before the exit marker, should
+   ;; never be skipped
+   ;;
+   (not (zerop (yas/field-number field)))))
 
 (defun yas/snippets-at-point (&optional all-snippets)
   "Return a sorted list of snippets at point, most recently
@@ -2918,7 +2887,7 @@ inserted first."
                                               (overlay-get ov 'yas/snippet))
                                           (if all-snippets
                                               (overlays-in (point-min) (point-max))
-                                            (overlays-at (point))))))
+                                            (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
    #'(lambda (s1 s2)
        (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
 
@@ -2947,7 +2916,7 @@ delegate to `yas/next-field'."
                                  (yas/snippet-fields snippet)))
          (active-field-pos (position active-field live-fields))
          (target-pos (and active-field-pos (+ arg active-field-pos)))
-         (target-field (nth target-pos live-fields)))
+         (target-field (and target-pos (nth target-pos live-fields))))
     ;; First check if we're moving out of a field with a transform
     ;;
     (when (and active-field
@@ -2959,7 +2928,7 @@ delegate to `yas/next-field'."
         ;; primary field transform: exit call to field-transform
         (yas/eval-lisp (yas/field-transform active-field))))
     ;; Now actually move...
-    (cond ((>= target-pos (length live-fields))
+    (cond ((and target-pos (>= target-pos (length live-fields)))
            (yas/exit-snippet snippet))
           (target-field
            (yas/move-to-field snippet target-field))
@@ -2976,15 +2945,23 @@ delegate to `yas/next-field'."
 
 Also create some protection overlays"
   (goto-char (yas/field-start field))
-  (setf (yas/snippet-active-field snippet) field)
   (yas/place-overlays snippet field)
   (overlay-put yas/active-field-overlay 'yas/field field)
-  ;; primary field transform: first call to snippet transform
-  (unless (yas/field-modified-p field)
-    (if (yas/field-update-display field snippet)
-        (let ((inhibit-modification-hooks t))
-          (yas/update-mirrors snippet))
-      (setf (yas/field-modified-p field) nil))))
+  (let ((number (yas/field-number field)))
+    ;; check for the special ${0: ...} field
+    (if (and number (zerop number))
+        (progn
+          (set-mark (yas/field-end field))
+          (setf (yas/snippet-force-exit snippet)
+                (or (yas/field-transform field)
+                    t)))
+      ;; make this field active
+      (setf (yas/snippet-active-field snippet) field)
+      ;; primary field transform: first call to snippet transform
+      (unless (yas/field-modified-p field)
+        (if (yas/field-update-display field snippet)
+            (yas/update-mirrors snippet)
+          (setf (yas/field-modified-p field) nil))))))
 
 (defun yas/prev-field ()
   "Navigate to prev field.  If there's none, exit the snippet."
@@ -3000,11 +2977,12 @@ Also create some protection overlays"
 
 (defun yas/exit-snippet (snippet)
   "Goto exit-marker of SNIPPET."
-  (interactive)
-  (setf (yas/snippet-force-exit snippet) t)
-  (goto-char (if (yas/snippet-exit snippet)
-                 (yas/exit-marker (yas/snippet-exit snippet))
-               (overlay-end (yas/snippet-control-overlay snippet)))))
+  (interactive (list (first (yas/snippets-at-point))))
+  (when snippet
+    (setf (yas/snippet-force-exit snippet) t)
+    (goto-char (if (yas/snippet-exit snippet)
+                   (yas/exit-marker (yas/snippet-exit snippet))
+                 (overlay-end (yas/snippet-control-overlay snippet))))))
 
 (defun yas/exit-all-snippets ()
   "Exit all snippets."
@@ -3012,23 +2990,25 @@ Also create some protection overlays"
   (mapc #'(lambda (snippet)
             (yas/exit-snippet snippet)
             (yas/check-commit-snippet))
-        (yas/snippets-at-point)))
+        (yas/snippets-at-point 'all-snippets)))
 
 \f
 ;;; Some low level snippet-routines
 
-(defun yas/commit-snippet (snippet &optional no-hooks)
-  "Commit SNIPPET, but leave point as it is.  This renders the
-snippet as ordinary text.
+(defmacro yas/inhibit-overlay-hooks (&rest body)
+  "Run BODY with `yas/inhibit-overlay-hooks' set to t."
+  (declare (indent 0))
+  `(let ((yas/inhibit-overlay-hooks t))
+     (progn ,@body)))
 
-Return a buffer position where the point should be placed if
-exiting the snippet.
+(defvar yas/snippet-beg nil "Beginning position of the last snippet commited.")
+(defvar yas/snippet-end nil "End position of the last snippet commited.")
 
-NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
+(defun yas/commit-snippet (snippet)
+  "Commit SNIPPET, but leave point as it is.  This renders the
+snippet as ordinary text."
 
-  (let ((control-overlay (yas/snippet-control-overlay snippet))
-        yas/snippet-beg
-        yas/snippet-end)
+  (let ((control-overlay (yas/snippet-control-overlay snippet)))
     ;;
     ;; Save the end of the moribund snippet in case we need to revive it
     ;; its original expansion.
@@ -3039,7 +3019,7 @@ NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
       (setq yas/snippet-end (overlay-end control-overlay))
       (delete-overlay control-overlay))
 
-    (let ((inhibit-modification-hooks t))
+    (yas/inhibit-overlay-hooks
       (when yas/active-field-overlay
         (delete-overlay yas/active-field-overlay))
       (when yas/field-protection-overlays
@@ -3064,30 +3044,31 @@ NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
               buffer-undo-list)
       ;; Dismember the snippet... this is useful if we get called
       ;; again from `yas/take-care-of-redo'....
-      (setf (yas/snippet-fields snippet) nil))
+      (setf (yas/snippet-fields snippet) nil)))
 
-    ;; XXX: `yas/after-exit-snippet-hook' should be run with
-    ;; `yas/snippet-beg' and `yas/snippet-end' bound. That might not
-    ;; be the case if the main overlay had somehow already
-    ;; disappeared, which sometimes happens when the snippet's messed
-    ;; up...
-    ;;
-    (unless no-hooks (run-hooks 'yas/after-exit-snippet-hook)))
+  (yas/message 3 "Snippet %s exited." (yas/snippet-id snippet)))
+
+(defun yas/safely-run-hooks (hook-var)
+  (condition-case error
+      (run-hooks hook-var)
+    (error
+     (yas/message 3 "%s error: %s" hook-var (error-message-string error)))))
 
-  (message "[yas] snippet exited."))
 
 (defun yas/check-commit-snippet ()
   "Checks if point exited the currently active field of the
 snippet, if so cleans up the whole snippet up."
   (let* ((snippets (yas/snippets-at-point 'all-snippets))
-         (snippets-left snippets))
+         (snippets-left snippets)
+         (snippet-exit-transform))
     (dolist (snippet snippets)
       (let ((active-field (yas/snippet-active-field snippet)))
-        (cond ((or (prog1 (yas/snippet-force-exit snippet)
-                     (setf (yas/snippet-force-exit snippet) nil))
+        (setq snippet-exit-transform (yas/snippet-force-exit snippet))
+        (cond ((or snippet-exit-transform
                    (not (and active-field (yas/field-contains-point-p active-field))))
                (setq snippets-left (delete snippet snippets-left))
-               (yas/commit-snippet snippet snippets-left))
+               (setf (yas/snippet-force-exit snippet) nil)
+               (yas/commit-snippet snippet))
               ((and active-field
                     (or (not yas/active-field-overlay)
                         (not (overlay-buffer yas/active-field-overlay))))
@@ -3101,9 +3082,10 @@ snippet, if so cleans up the whole snippet up."
                  (yas/update-mirrors snippet)))
               (t
                nil))))
-    (unless snippets-left
-      (remove-hook 'post-command-hook 'yas/post-command-handler 'local)
-      (remove-hook 'pre-command-hook 'yas/pre-command-handler 'local))))
+    (unless (or (null snippets) snippets-left)
+      (if snippet-exit-transform
+          (yas/eval-lisp-no-saves snippet-exit-transform))
+      (yas/safely-run-hooks 'yas/after-exit-snippet-hook))))
 
 ;; Apropos markers-to-points:
 ;;
@@ -3184,6 +3166,7 @@ holds the keymap."
                                nil
                                t)))
     (overlay-put overlay 'keymap yas/keymap)
+    (overlay-put overlay 'priority 100)
     (overlay-put overlay 'yas/snippet snippet)
     overlay))
 
@@ -3246,27 +3229,25 @@ Move the overlay, or create it if it does not exit."
     (overlay-put yas/active-field-overlay 'insert-behind-hooks
                  '(yas/on-field-overlay-modification))))
 
+(defvar yas/inhibit-overlay-hooks nil
+  "Bind this temporarity to non-nil to prevent running `yas/on-*-modification'.")
+
 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
   "Clears the field and updates mirrors, conditionally.
 
 Only clears the field if it hasn't been modified and it point it
 at field start. This hook doesn't do anything if an undo is in
 progress."
-  (unless (yas/undo-in-progress)
-    (let* ((field (overlay-get yas/active-field-overlay 'yas/field))
+  (unless (or yas/inhibit-overlay-hooks
+              (yas/undo-in-progress))
+    (let* ((field (overlay-get overlay 'yas/field))
            (number (and field (yas/field-number field)))
            (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
       (cond (after?
              (yas/advance-end-maybe field (overlay-end overlay))
-             ;; primary field transform: normal calls to expression or
-             ;; force an exit on next `post-command-hook' if the
-             ;; number is 0
-             (if (and number (zerop number))
-                 (setf (yas/snippet-force-exit snippet) t)
-               (let ((saved-point (point)))
-                 (yas/field-update-display field (car (yas/snippets-at-point)))
-                 (goto-char saved-point)))
-             (yas/update-mirrors (car (yas/snippets-at-point))))
+             (save-excursion
+               (yas/field-update-display field snippet))
+             (yas/update-mirrors snippet))
             (field
              (when (and (not after?)
                         (not (yas/field-modified-p field))
@@ -3307,7 +3288,7 @@ Move the overlays, or create them if they do not exit."
     ;;
     (when (< (buffer-size) end)
       (save-excursion
-        (let ((inhibit-modification-hooks t))
+        (yas/inhibit-overlay-hooks
           (goto-char (point-max))
           (newline))))
     ;; go on to normal overlay creation/moving
@@ -3338,10 +3319,11 @@ originated")
   "Signals a snippet violation, then issues error.
 
 The error should be ignored in `debug-ignored-errors'"
-  (cond ((not (or after?
-                  (yas/undo-in-progress)))
-         (setq yas/protection-violation (point))
-         (error "Exit the snippet first!"))))
+  (unless yas/inhibit-overlay-hooks
+    (cond ((not (or after?
+                    (yas/undo-in-progress)))
+           (setq yas/protection-violation (point))
+           (error "Exit the snippet first!")))))
 
 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
 
@@ -3379,7 +3361,7 @@ considered when expanding the snippet."
 
   ;; If a region is active, set `yas/selected-text'
   (setq yas/selected-text
-        (when mark-active
+        (when (region-active-p)
           (prog1 (buffer-substring-no-properties (region-beginning)
                                                  (region-end))
             (unless start (setq start (region-beginning))
@@ -3392,14 +3374,13 @@ considered when expanding the snippet."
   (let ((to-delete (and start end (buffer-substring-no-properties start end)))
         (start (or start (point)))
         (end (or end (point)))
-        (column (current-column))
         snippet)
+    (setq yas/indent-original-column (current-column))
     ;; Delete the region to delete, this *does* get undo-recorded.
     ;;
     (when (and to-delete
                (> end start))
-      (delete-region start end)
-      (setq yas/deleted-text to-delete))
+      (delete-region start end))
 
     (cond ((listp content)
            ;; x) This is a snippet-command
@@ -3417,21 +3398,20 @@ considered when expanding the snippet."
            ;;    stacked expansion: also shoosh the overlay modification hooks
            (save-restriction
              (narrow-to-region start start)
-             (let ((inhibit-modification-hooks t)
-                   (buffer-undo-list t))
+             (let ((buffer-undo-list t))
                ;; snippet creation might evaluate users elisp, which
                ;; might generate errors, so we have to be ready to catch
                ;; them mostly to make the undo information
                ;;
                (setq yas/start-column (save-restriction (widen) (current-column)))
-
-               (setq snippet
-                     (if expand-env
-                         (eval `(let ,expand-env
-                                  (insert content)
-                                  (yas/snippet-create (point-min) (point-max))))
-                       (insert content)
-                       (yas/snippet-create (point-min) (point-max))))))
+               (yas/inhibit-overlay-hooks
+                 (setq snippet
+                       (if expand-env
+                           (eval `(let* ,expand-env
+                                    (insert content)
+                                    (yas/snippet-create (point-min) (point-max))))
+                         (insert content)
+                         (yas/snippet-create (point-min) (point-max)))))))
 
            ;; stacked-expansion: This checks for stacked expansion, save the
            ;; `yas/previous-active-field' and advance its boudary.
@@ -3470,8 +3450,9 @@ considered when expanding the snippet."
            (let ((first-field (car (yas/snippet-fields snippet))))
              (when first-field
                (sit-for 0) ;; fix issue 125
-               (yas/move-to-field snippet first-field))))
-          (message "[yas] snippet expanded."))))
+               (yas/move-to-field snippet first-field)))
+           (yas/message 3 "snippet expanded.")
+           t))))
 
 (defun yas/take-care-of-redo (beg end snippet)
   "Commits SNIPPET, which in turn pushes an undo action for
@@ -3481,7 +3462,7 @@ Meant to exit in the `buffer-undo-list'."
   ;; slightly optimize: this action is only needed for snippets with
   ;; at least one field
   (when (yas/snippet-fields snippet)
-    (yas/commit-snippet snippet 'no-hooks)))
+    (yas/commit-snippet snippet)))
 
 (defun yas/snippet-revive (beg end snippet)
   "Revives the SNIPPET and creates a control overlay from BEG to
@@ -3507,9 +3488,6 @@ After revival, push the `yas/take-care-of-redo' in the
 
       (yas/move-to-field snippet target-field)
 
-      (add-hook 'post-command-hook 'yas/post-command-handler nil t)
-      (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
-
       (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
             buffer-undo-list))))
 
@@ -3531,10 +3509,6 @@ Returns the newly created snippet."
     ;; Move to end
     (goto-char (point-max))
 
-    ;; Setup hooks
-    (add-hook 'post-command-hook 'yas/post-command-handler nil t)
-    (add-hook 'pre-command-hook 'yas/pre-command-handler t t)
-
     snippet))
 
 \f
@@ -3655,9 +3629,7 @@ exit-marker have identical start and end markers.
   (cond ((and fom (< (yas/fom-end fom) newend))
          (set-marker (yas/fom-end fom) newend)
          (yas/advance-start-maybe (yas/fom-next fom) newend)
-         (let ((parent (yas/fom-parent-field fom)))
-           (when parent
-             (yas/advance-end-maybe parent newend))))
+         (yas/advance-end-of-parents-maybe (yas/fom-parent-field fom) newend))
         ((yas/exit-p fom)
          (yas/advance-start-maybe (yas/fom-next fom) newend))))
 
@@ -3670,7 +3642,10 @@ If it does, also call `yas/advance-end-maybe' on FOM."
     (yas/advance-end-maybe fom newstart)))
 
 (defun yas/advance-end-of-parents-maybe (field newend)
-  "Like `yas/advance-end-maybe' but for parents."
+  "Like `yas/advance-end-maybe' but for parent fields.
+
+Only works for fields and doesn't care about the start of the
+next FOM. Works its way up recursively for parents of parents."
   (when (and field
              (< (yas/field-end field) newend))
     (set-marker (yas/field-end field) newend)
@@ -3691,7 +3666,7 @@ Meant to be called in a narrowed buffer, does various passes"
     (setq yas/dollar-regions nil)
     ;; protect escaped quote, backquotes and backslashes
     ;;
-    (yas/protect-escapes nil '(?\\ ?` ?'))
+    (yas/protect-escapes nil `(?\\ ?` ?'))
     ;; replace all backquoted expressions
     ;;
     (goto-char parse-start)
@@ -3760,12 +3735,13 @@ SNIPPET-MARKERS."
       (widen)
       (condition-case err
           (indent-according-to-mode)
-        (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
+        (error (yas/message 3 "Warning: `yas/indent-according-to-mode' having problems running %s" indent-line-function)
                nil)))
     (mapc #'(lambda (marker)
               (set-marker marker (point)))
           trouble-markers)))
 
+(defvar yas/indent-original-column nil)
 (defun yas/indent (snippet)
   (let ((snippet-markers (yas/collect-snippet-markers snippet)))
     ;; Look for those $>
@@ -3779,7 +3755,7 @@ SNIPPET-MARKERS."
       (cond ((eq yas/indent-line 'fixed)
              (while (and (zerop (forward-line))
                          (zerop (current-column)))
-               (indent-to-column column)))
+               (indent-to-column yas/indent-original-column)))
             ((eq yas/indent-line 'auto)
              (let ((end (set-marker (make-marker) (point-max)))
                    (indent-first-line-p yas/also-auto-indent-first-line))
@@ -3851,12 +3827,13 @@ With optional string TEXT do it in string instead of the buffer."
 
 (defun yas/replace-backquotes ()
   "Replace all the \"`(lisp-expression)`\"-style expression
-  with their evaluated value"
+       with their evaluated value"
   (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
-    (let ((transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes (match-string 1))))))
-      (goto-char (match-end 0))
-      (when transformed (insert transformed))
-      (delete-region (match-beginning 0) (match-end 0)))))
+    (let ((current-string (match-string 1)) transformed)
+      (delete-region (match-beginning 0) (match-end 0))
+      (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
+      (goto-char (match-beginning 0))
+      (when transformed (insert transformed)))))
 
 (defun yas/scan-sexps (from count)
   (condition-case err
@@ -4022,12 +3999,7 @@ When multiple expressions are found, only the last one counts."
            (field (car fields)))
       (while field
         (dolist (mirror (yas/field-mirrors field))
-          ;; stacked expansion: I added an `inhibit-modification-hooks'
-          ;; here, for safety, may need to remove if we the mechanism is
-          ;; altered.
-          ;;
-          (let ((inhibit-modification-hooks t)
-                (mirror-parent-field (yas/mirror-parent-field mirror)))
+          (let ((mirror-parent-field (yas/mirror-parent-field mirror)))
             ;; updatte this mirror
             ;;
             (yas/mirror-update-display mirror field)
@@ -4051,13 +4023,14 @@ When multiple expressions are found, only the last one counts."
   (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
          (reflection (and (not (and mirror-parent-field
                                     (yas/field-modified-p mirror-parent-field)))
-                          (or (yas/apply-transform mirror field)
+                          (or (yas/apply-transform mirror field 'empty-on-nil)
                               (yas/field-text-for-display field)))))
     (when (and reflection
                (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
                                                                         (yas/mirror-end mirror)))))
       (goto-char (yas/mirror-start mirror))
-      (insert reflection)
+      (yas/inhibit-overlay-hooks
+        (insert reflection))
       (if (> (yas/mirror-end mirror) (point))
           (delete-region (point) (yas/mirror-end mirror))
         (set-marker (yas/mirror-end mirror) (point))
@@ -4068,26 +4041,27 @@ When multiple expressions are found, only the last one counts."
 (defun yas/field-update-display (field snippet)
   "Much like `yas/mirror-update-display', but for fields"
   (when (yas/field-transform field)
-    (let ((inhibit-modification-hooks t)
-          (transformed (yas/apply-transform field field))
+    (let ((transformed (and (not (eq (yas/field-number field) 0))
+                            (yas/apply-transform field field)))
           (point (point)))
       (when (and transformed
                  (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
                                                                            (yas/field-end field)))))
         (setf (yas/field-modified-p field) t)
         (goto-char (yas/field-start field))
-        (insert transformed)
-        (if (> (yas/field-end field) (point))
-            (delete-region (point) (yas/field-end field))
-          (set-marker (yas/field-end field) (point))
-          (yas/advance-start-maybe (yas/field-next field) (point)))
-        t))))
+        (yas/inhibit-overlay-hooks
+          (insert transformed)
+          (if (> (yas/field-end field) (point))
+              (delete-region (point) (yas/field-end field))
+            (set-marker (yas/field-end field) (point))
+            (yas/advance-start-maybe (yas/field-next field) (point)))
+          t)))))
 
 \f
-;;; Pre- and post-command hooks:
+;;; Post-command hooks:
 
 (defvar yas/post-command-runonce-actions nil
-  "List of actions to run once  `post-command-hook'.
+  "List of actions to run once in `post-command-hook'.
 
 Each element of this list looks like (FN . ARGS) where FN is
 called with ARGS as its arguments after the currently executing
@@ -4096,8 +4070,6 @@ snippet command.
 After all actions have been run, this list is emptied, and after
 that the rest of `yas/post-command-handler' runs.")
 
-(defun yas/pre-command-handler () )
-
 (defun yas/post-command-handler ()
   "Handles various yasnippet conditions after each command."
   (when yas/post-command-runonce-actions
@@ -4106,7 +4078,7 @@ that the rest of `yas/post-command-handler' runs.")
                   (apply (car fn-and-args)
                          (cdr fn-and-args)))
               yas/post-command-runonce-actions)
-      (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
+      (error (yas/message 3 "Problem running `yas/post-command-runonce-actions'!")))
     (setq yas/post-command-runonce-actions nil))
   (cond (yas/protection-violation
          (goto-char yas/protection-violation)
@@ -4132,7 +4104,8 @@ that the rest of `yas/post-command-handler' runs.")
 \f
 ;;; Fancy docs:
 
-(put 'yas/expand  'function-documentation '(yas/expand-from-trigger-key-doc))
+(put 'yas/expand  'function-documentation
+     '(yas/expand-from-trigger-key-doc))
 (defun yas/expand-from-trigger-key-doc ()
   "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
   (let ((fallback-description
@@ -4195,11 +4168,12 @@ object satisfying `yas/field-p' to restrict the expansion to.")))
 (defun yas/create-snippet-xrefs ()
   (save-excursion
     (goto-char (point-min))
-    (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+\\(`[^']+'\\)" nil t)
+    (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
       (let ((template (get-text-property (match-beginning 1)
                                          'yasnippet)))
         (when template
           (help-xref-button 1 'help-snippet-def template)
+          (kill-region (match-end 1) (match-end 0))
           (kill-region (match-beginning 0) (match-beginning 1)))))))
 
 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
@@ -4211,15 +4185,34 @@ Remaining args as in `yas/expand-snippet'."
                                     (gethash uuid (yas/table-uuidhash table)))))
     (when yas/current-template
       (yas/expand-snippet (yas/template-content yas/current-template)))))
+\f
+;;; Utils
+;;;
+
+(defvar yas/verbosity 4
+  "Log level for `yas/message' 4 means trace most anything, 0 means nothing.")
+(defun yas/message (level message &rest args)
+  (when (> yas/verbosity level)
+    (message (apply #'yas/format message args))))
+
+(defun yas/format (format-control &rest format-args)
+  (apply #'format (concat "[yas] " format-control) format-args))
 
 \f
 ;;; Some hacks:
-;; `locate-dominating-file' is added for compatibility in emacs < 23
-(unless (or (eq emacs-major-version 23)
-            (fboundp 'locate-dominating-file))
-  (defvar locate-dominating-stop-dir-regexp
-    "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
-    "Regexp of directory names which stop the search in `locate-dominating-file'.
+;;;
+;; `locate-dominating-file'
+;; `region-active-p'
+;;
+;; added for compatibility in emacs < 23
+(unless (>= emacs-major-version 23)
+  (unless (fboundp 'region-active-p)
+    (defun region-active-p ()  (and transient-mark-mode mark-active)))
+
+  (unless (fboundp 'locate-dominating-file)
+    (defvar locate-dominating-stop-dir-regexp
+      "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
+      "Regexp of directory names which stop the search in `locate-dominating-file'.
 Any directory whose name matches this regexp will be treated like
 a kind of root directory by `locate-dominating-file' which will stop its search
 when it bumps into it.
@@ -4227,44 +4220,44 @@ The default regexp prevents fruitless and time-consuming attempts to find
 special files in directories in which filenames are interpreted as hostnames,
 or mount points potentially requiring authentication as a different user.")
 
-  (defun locate-dominating-file (file name)
-    "Look up the directory hierarchy from FILE for a file named NAME.
+    (defun locate-dominating-file (file name)
+      "Look up the directory hierarchy from FILE for a file named NAME.
 Stop at the first parent directory containing a file NAME,
 and return the directory.  Return nil if not found."
-    ;; We used to use the above locate-dominating-files code, but the
-    ;; directory-files call is very costly, so we're much better off doing
-    ;; multiple calls using the code in here.
-    ;;
-    ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
-    ;; `name' in /home or in /.
-    (setq file (abbreviate-file-name file))
-    (let ((root nil)
-          (prev-file file)
-          ;; `user' is not initialized outside the loop because
-          ;; `file' may not exist, so we may have to walk up part of the
-          ;; hierarchy before we find the "initial UUID".
-          (user nil)
-          try)
-      (while (not (or root
-                      (null file)
-                      ;; FIXME: Disabled this heuristic because it is sometimes
-                      ;; inappropriate.
-                      ;; As a heuristic, we stop looking up the hierarchy of
-                      ;; directories as soon as we find a directory belonging
-                      ;; to another user.  This should save us from looking in
-                      ;; things like /net and /afs.  This assumes that all the
-                      ;; files inside a project belong to the same user.
-                      ;; (let ((prev-user user))
-                      ;;   (setq user (nth 2 (file-attributes file)))
-                      ;;   (and prev-user (not (equal user prev-user))))
-                      (string-match locate-dominating-stop-dir-regexp file)))
-        (setq try (file-exists-p (expand-file-name name file)))
-        (cond (try (setq root file))
-              ((equal file (setq prev-file file
-                                 file (file-name-directory
-                                       (directory-file-name file))))
-               (setq file nil))))
-      root)))
+      ;; We used to use the above locate-dominating-files code, but the
+      ;; directory-files call is very costly, so we're much better off doing
+      ;; multiple calls using the code in here.
+      ;;
+      ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
+      ;; `name' in /home or in /.
+      (setq file (abbreviate-file-name file))
+      (let ((root nil)
+            (prev-file file)
+            ;; `user' is not initialized outside the loop because
+            ;; `file' may not exist, so we may have to walk up part of the
+            ;; hierarchy before we find the "initial UUID".
+            (user nil)
+            try)
+        (while (not (or root
+                        (null file)
+                        ;; FIXME: Disabled this heuristic because it is sometimes
+                        ;; inappropriate.
+                        ;; As a heuristic, we stop looking up the hierarchy of
+                        ;; directories as soon as we find a directory belonging
+                        ;; to another user.  This should save us from looking in
+                        ;; things like /net and /afs.  This assumes that all the
+                        ;; files inside a project belong to the same user.
+                        ;; (let ((prev-user user))
+                        ;;   (setq user (nth 2 (file-attributes file)))
+                        ;;   (and prev-user (not (equal user prev-user))))
+                        (string-match locate-dominating-stop-dir-regexp file)))
+          (setq try (file-exists-p (expand-file-name name file)))
+          (cond (try (setq root file))
+                ((equal file (setq prev-file file
+                                   file (file-name-directory
+                                         (directory-file-name file))))
+                 (setq file nil))))
+        root))))
 
 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
 ;; (when it execute forward-char) and interrupt the after change