Path: blob/master/elisp/emacs-for-python/yasnippet/yasnippet.el
990 views
;;; Yasnippet.el --- Yet another snippet extension for Emacs.12;; Copyright 2008 pluskid3;; 2009 pluskid, joaotavora45;; Authors: pluskid <[email protected]>, joaotavora <[email protected]>6;; Version: 0.7.07;; Package-version: 0.7.08;; X-URL: http://code.google.com/p/yasnippet/9;; Keywords: convenience, emulation10;; URL: http://code.google.com/p/yasnippet/11;; EmacsWiki: YaSnippetMode1213;; This file is free software; you can redistribute it and/or modify14;; it under the terms of the GNU General Public License as published by15;; the Free Software Foundation; either version 2, or (at your option)16;; any later version.1718;; This file is distributed in the hope that it will be useful,19;; but WITHOUT ANY WARRANTY; without even the implied warranty of20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the21;; GNU General Public License for more details.2223;; You should have received a copy of the GNU General Public License24;; along with GNU Emacs; see the file COPYING. If not, write to25;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,26;; Boston, MA 02111-1307, USA.2728;;; Commentary:2930;; Basic steps to setup:31;;32;; 1. In your .emacs file:33;; (add-to-list 'load-path "/dir/to/yasnippet.el")34;; (require 'yasnippet)35;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets36;; 3. In your .emacs file37;; (setq yas/snippet-dirs "~/.emacs/snippets")38;; (yas/load-directory yas/snippet-dirs)39;; 4. To enable the YASnippet menu and tab-trigger expansion40;; M-x yas/minor-mode41;; 5. To globally enable the minor mode in *all* buffers42;; M-x yas/global-mode43;;44;; Steps 4. and 5. are optional, you don't have to use the minor45;; mode to use YASnippet.46;;47;; Interesting variables are:48;;49;; `yas/snippet-dirs'50;;51;; The directory where user-created snippets are to be52;; stored. Can also be a list of directories. In that case,53;; when used for bulk (re)loading of snippets (at startup or54;; via `yas/reload-all'), directories appearing earlier in55;; the list shadow other dir's snippets. Also, the first56;; directory is taken as the default for storing the user's57;; new snippets.58;;59;; The deprecated `yas/root-directory' aliases this variable60;; for backward-compatibility.61;;62;; `yas/extra-modes'63;;64;; A local variable that you can set in a hook to override65;; snippet-lookup based on major mode. It is a a symbol (or66;; list of symbols) that correspond to subdirectories of67;; `yas/snippet-dirs' and is used for deciding which68;; snippets to consider for the active buffer.69;;70;; Deprecated `yas/mode-symbol' aliases this variable for71;; backward-compatibility.72;;73;; Major commands are:74;;75;; M-x yas/expand76;;77;; Try to expand snippets before point. In `yas/minor-mode',78;; this is bound to `yas/trigger-key' which you can customize.79;;80;; M-x yas/load-directory81;;82;; Prompts you for a directory hierarchy of snippets to load.83;;84;; M-x yas/insert-snippet85;;86;; Prompts you for possible snippet expansion if that is87;; possible according to buffer-local and snippet-local88;; expansion conditions. With prefix argument, ignore these89;; conditions.90;;91;; M-x yas/find-snippets92;;93;; Lets you find the snippet files in the correct94;; subdirectory of `yas/snippet-dirs', according to the95;; active major mode (if it exists) like96;; `find-file-other-window'.97;;98;; M-x yas/visit-snippet-file99;;100;; Prompts you for possible snippet expansions like101;; `yas/insert-snippet', but instead of expanding it, takes102;; you directly to the snippet definition's file, if it103;; exists.104;;105;; M-x yas/new-snippet106;;107;; Lets you create a new snippet file in the correct108;; subdirectory of `yas/snippet-dirs', according to the109;; active major mode.110;;111;; M-x yas/load-snippet-buffer112;;113;; When editing a snippet, this loads the snippet. This is114;; bound to "C-c C-c" while in the `snippet-mode' editing115;; mode.116;;117;; M-x yas/tryout-snippet118;;119;; When editing a snippet, this opens a new empty buffer,120;; sets it to the appropriate major mode and inserts the121;; snippet there, so you can see what it looks like. This is122;; bound to "C-c C-t" while in `snippet-mode'.123;;124;; M-x yas/describe-tables125;;126;; Lists known snippets in a separate buffer. User is127;; prompted as to whether only the currently active tables128;; are to be displayed, or all the tables for all major129;; modes.130;;131;; The `dropdown-list.el' extension is bundled with YASnippet, you132;; can optionally use it the preferred "prompting method", puting in133;; your .emacs file, for example:134;;135;; (require 'dropdown-list)136;; (setq yas/prompt-functions '(yas/dropdown-prompt137;; yas/ido-prompt138;; yas/completing-prompt))139;;140;; Also check out the customization group141;;142;; M-x customize-group RET yasnippet RET143;;144;; If you use the customization group to set variables145;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to146;; "yasnippet.el" is present in the `load-path' *before* the147;; `custom-set-variables' is executed in your .emacs file.148;;149;; For more information and detailed usage, refer to the project page:150;; http://code.google.com/p/yasnippet/151152;;; Code:153154(require 'cl)155(require 'assoc)156(require 'easymenu)157(require 'help-mode)158159160;;; User customizable variables161162(defgroup yasnippet nil163"Yet Another Snippet extension"164:group 'editing)165166;;;###autoload167(defcustom yas/snippet-dirs nil168"Directory or list of snippet dirs for each major mode.169170The directory where user-created snippets are to be stored. Can171also be a list of directories. In that case, when used for172bulk (re)loading of snippets (at startup or via173`yas/reload-all'), directories appearing earlier in the list174shadow other dir's snippets. Also, the first directory is taken175as the default for storing the user's new snippets."176:type '(choice (string :tag "Single directory (string)")177(repeat :args (string) :tag "List of directories (strings)"))178:group 'yasnippet179:require 'yasnippet180:set #'(lambda (symbol new)181(let ((old (and (boundp symbol)182(symbol-value symbol))))183(set-default symbol new)184(unless (or (not (fboundp 'yas/reload-all))185(equal old new))186(yas/reload-all)))))187(defun yas/snippet-dirs ()188(if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))189(defvaralias 'yas/root-directory 'yas/snippet-dirs)190191(defcustom yas/prompt-functions '(yas/x-prompt192yas/dropdown-prompt193yas/completing-prompt194yas/ido-prompt195yas/no-prompt)196"Functions to prompt for keys, templates, etc interactively.197198These functions are called with the following arguments:199200- PROMPT: A string to prompt the user201202- CHOICES: a list of strings or objects.203204- optional DISPLAY-FN : A function that, when applied to each of205the objects in CHOICES will return a string.206207The return value of any function you put here should be one of208the objects in CHOICES, properly formatted with DISPLAY-FN (if209that is passed).210211- To signal that your particular style of prompting is212unavailable at the moment, you can also have the function return213nil.214215- To signal that the user quit the prompting process, you can216signal `quit' with217218(signal 'quit \"user quit!\")."219:type '(repeat function)220:group 'yasnippet)221222(defcustom yas/indent-line 'auto223"Controls indenting applied to a recent snippet expansion.224225The following values are possible:226227- `fixed' Indent the snippet to the current column;228229- `auto' Indent each line of the snippet with `indent-according-to-mode'230231Every other value means don't apply any snippet-side indendation232after expansion (the manual per-line \"$>\" indentation still233applies)."234:type '(choice (const :tag "Nothing" nothing)235(const :tag "Fixed" fixed)236(const :tag "Auto" auto))237:group 'yasnippet)238239(defcustom yas/also-auto-indent-first-line nil240"Non-nil means also auto indent first line according to mode.241242Naturally this is only valid when `yas/indent-line' is `auto'"243:type 'boolean244:group 'yasnippet)245246(defcustom yas/snippet-revival t247"Non-nil means re-activate snippet fields after undo/redo."248:type 'boolean249:group 'yasnippet)250251(defcustom yas/trigger-key "TAB"252"The key bound to `yas/expand' when function `yas/minor-mode' is active.253254Value is a string that is converted to the internal Emacs key255representation using `read-kbd-macro'."256:type 'string257:group 'yasnippet258:set #'(lambda (symbol key)259(let ((old (and (boundp symbol)260(symbol-value symbol))))261(set-default symbol key)262;; On very first loading of this defcustom,263;; `yas/trigger-key' is *not* loaded.264(if (fboundp 'yas/trigger-key-reload)265(yas/trigger-key-reload old)))))266267(defcustom yas/next-field-key '("TAB" "<tab>")268"The key to navigate to next field when a snippet is active.269270Value is a string that is converted to the internal Emacs key271representation using `read-kbd-macro'.272273Can also be a list of strings."274:type '(choice (string :tag "String")275(repeat :args (string) :tag "List of strings"))276:group 'yasnippet277:set #'(lambda (symbol val)278(set-default symbol val)279(if (fboundp 'yas/init-yas-in-snippet-keymap)280(yas/init-yas-in-snippet-keymap))))281282283(defcustom yas/prev-field-key '("<backtab>" "<S-tab>")284"The key to navigate to previous field when a snippet is active.285286Value is a string that is converted to the internal Emacs key287representation using `read-kbd-macro'.288289Can also be a list of strings."290:type '(choice (string :tag "String")291(repeat :args (string) :tag "List of strings"))292:group 'yasnippet293:set #'(lambda (symbol val)294(set-default symbol val)295(if (fboundp 'yas/init-yas-in-snippet-keymap)296(yas/init-yas-in-snippet-keymap))))297298(defcustom yas/skip-and-clear-key "C-d"299"The key to clear the currently active field.300301Value is a string that is converted to the internal Emacs key302representation using `read-kbd-macro'.303304Can also be a list of strings."305:type '(choice (string :tag "String")306(repeat :args (string) :tag "List of strings"))307:group 'yasnippet308:set #'(lambda (symbol val)309(set-default symbol val)310(if (fboundp 'yas/init-yas-in-snippet-keymap)311(yas/init-yas-in-snippet-keymap))))312313(defcustom yas/triggers-in-field nil314"If non-nil, `yas/next-field-key' can trigger stacked expansions.315316Otherwise, `yas/next-field-key' just tries to move on to the next317field"318:type 'boolean319:group 'yasnippet)320321(defcustom yas/fallback-behavior 'call-other-command322"How to act when `yas/trigger-key' does *not* expand a snippet.323324- `call-other-command' means try to temporarily disable YASnippet325and call the next command bound to `yas/trigger-key'.326327- nil or the symbol `return-nil' mean do nothing. (and328`yas/expand-returns' nil)329330- A lisp form (apply COMMAND . ARGS) means interactively call331COMMAND, if ARGS is non-nil, call COMMAND non-interactively332with ARGS as arguments."333:type '(choice (const :tag "Call previous command" call-other-command)334(const :tag "Do nothing" return-nil))335:group 'yasnippet)336337(defcustom yas/choose-keys-first nil338"If non-nil, prompt for snippet key first, then for template.339340Otherwise prompts for all possible snippet names.341342This affects `yas/insert-snippet' and `yas/visit-snippet-file'."343:type 'boolean344:group 'yasnippet)345346(defcustom yas/choose-tables-first nil347"If non-nil, and multiple eligible snippet tables, prompts user for tables first.348349Otherwise, user chooses between the merging together of all350eligible tables.351352This affects `yas/insert-snippet', `yas/visit-snippet-file'"353:type 'boolean354:group 'yasnippet)355356(defcustom yas/use-menu 'abbreviate357"Display a YASnippet menu in the menu bar.358359When non-nil, submenus for each snippet table will be listed360under the menu \"Yasnippet\".361362- If set to `real-modes' only submenus whose name more or less363corresponds to a major mode are listed.364365- If set to `abbreviate', only the current major-mode366menu and the modes set in `yas/extra-modes' are listed.367368Any other non-nil value, every submenu is listed."369:type '(choice (const :tag "Full" t)370(const :tag "Real modes only" real-modes)371(const :tag "Abbreviate" abbreviate))372:group 'yasnippet)373374(defcustom yas/trigger-symbol " =>"375"The text that will be used in menu to represent the trigger."376:type 'string377:group 'yasnippet)378379(defcustom yas/wrap-around-region nil380"If non-nil, snippet expansion wraps around selected region.381382The wrapping occurs just before the snippet's exit marker. This383can be overriden on a per-snippet basis."384:type 'boolean385:group 'yasnippet)386387(defcustom yas/good-grace t388"If non-nil, don't raise errors in inline elisp evaluation.389390An error string \"[yas] error\" is returned instead."391:type 'boolean392:group 'yasnippet)393394(defcustom yas/ignore-filenames-as-triggers nil395"If non-nil, don't derive tab triggers from filenames.396397This means a snippet without a \"# key:'\ directive won't have a398tab trigger."399:type 'boolean400:group 'yasnippet)401402(defcustom yas/visit-from-menu nil403"If non-nil visit snippets's files from menu, instead of expanding them.404405This cafn only work when snippets are loaded from files."406:type 'boolean407:group 'yasnippet)408409(defcustom yas/expand-only-for-last-commands nil410"List of `last-command' values to restrict tab-triggering to, or nil.411412Leave this set at nil (the default) to be able to trigger an413expansion simply by placing the cursor after a valid tab trigger,414using whichever commands.415416Optionallly, set this to something like '(self-insert-command) if417you to wish restrict expansion to only happen when the last418letter of the snippet tab trigger was typed immediately before419the trigger key itself."420:type '(repeat function)421:group 'yasnippet)422423;; Only two faces, and one of them shouldn't even be used...424;;425(defface yas/field-highlight-face426'((t (:inherit 'region)))427"The face used to highlight the currently active field of a snippet"428:group 'yasnippet)429430(defface yas/field-debug-face431'()432"The face used for debugging some overlays normally hidden"433:group 'yasnippet)434435436;;; User can also customize the next defvars437(defun yas/define-some-keys (keys keymap definition)438"Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."439(let ((keys (or (and (listp keys) keys)440(list keys))))441(dolist (key keys)442(define-key keymap (read-kbd-macro key) definition))))443444(defvar yas/keymap445(let ((map (make-sparse-keymap)))446(mapc #'(lambda (binding)447(yas/define-some-keys (car binding) map (cdr binding)))448`((,yas/next-field-key . yas/next-field-or-maybe-expand)449(,yas/prev-field-key . yas/prev-field)450("C-g" . yas/abort-snippet)451(,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))452map)453"The keymap active while a snippet expansion is in progress.")454455(defvar yas/key-syntaxes (list "w" "w_" "w_.()" "^ ")456"A list of syntax of a key. This list is tried in the order457to try to find a key. For example, if the list is '(\"w\" \"w_\").458And in emacs-lisp-mode, where \"-\" has the syntax of \"_\":459460foo-bar461462will first try \"bar\", if not found, then \"foo-bar\" is tried.")463464(defvar yas/after-exit-snippet-hook465'()466"Hooks to run after a snippet exited.467468The hooks will be run in an environment where some variables bound to469proper values:470471`yas/snippet-beg' : The beginning of the region of the snippet.472473`yas/snippet-end' : Similar to beg.474475Attention: These hooks are not run when exiting nested/stackd snippet expansion!")476477(defvar yas/before-expand-snippet-hook478'()479"Hooks to run just before expanding a snippet.")480481(defvar yas/buffer-local-condition482'(if (and (or (fourth (syntax-ppss))483(fifth (syntax-ppss)))484(eq (symbol-function this-command) 'yas/expand-from-trigger-key))485'(require-snippet-condition . force-in-comment)486t)487"Snippet expanding condition.488489This variable is a lisp form:490491* If it evaluates to nil, no snippets can be expanded.492493* If it evaluates to the a cons (require-snippet-condition494. REQUIREMENT)495496* Snippets bearing no \"# condition:\" directive are not497considered498499* Snippets bearing conditions that evaluate to nil (or500produce an error) won't be onsidered.501502* If the snippet has a condition that evaluates to non-nil503RESULT:504505* If REQUIREMENT is t, the snippet is considered506507* If REQUIREMENT is `eq' RESULT, the snippet is508considered509510* Otherwise, the snippet is not considered.511512* If it evaluates to the symbol 'always, all snippets are513considered for expansion, regardless of any conditions.514515* If it evaluates to t or some other non-nil value516517* Snippet bearing no conditions, or conditions that518evaluate to non-nil, are considered for expansion.519520* Otherwise, the snippet is not considered.521522Here's an example preventing snippets from being expanded from523inside comments, in `python-mode' only, with the exception of524snippets returning the symbol 'force-in-comment in their525conditions.526527(add-hook 'python-mode-hook528'(lambda ()529(setq yas/buffer-local-condition530'(if (python-in-string/comment)531'(require-snippet-condition . force-in-comment)532t))))533534The default value is similar, it filters out potential snippet535expansions inside comments and string literals, unless the536snippet itself contains a condition that returns the symbol537`force-in-comment'.")538539540;;; Internal variables541542(defvar yas/version "0.7.0")543544(defvar yas/menu-table (make-hash-table)545"A hash table of MAJOR-MODE symbols to menu keymaps.")546547(defun teste ()548(interactive)549(message "AHAHA!"))550551(defvar yas/known-modes552'(ruby-mode rst-mode markdown-mode)553"A list of mode which is well known but not part of emacs.")554555(defvar yas/escaped-characters556'(?\\ ?` ?' ?$ ?} ?\( ?\))557"List of characters which *might* need to be escaped.")558559(defconst yas/field-regexp560"${\\([0-9]+:\\)?\\([^}]*\\)}"561"A regexp to *almost* recognize a field.")562563(defconst yas/multi-dollar-lisp-expression-regexp564"$+[ \t\n]*\\(([^)]*)\\)"565"A regexp to *almost* recognize a \"$(...)\" expression.")566567(defconst yas/backquote-lisp-expression-regexp568"`\\([^`]*\\)`"569"A regexp to recognize a \"`lisp-expression`\" expression." )570571(defconst yas/transform-mirror-regexp572"${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"573"A regexp to *almost* recognize a mirror with a transform.")574575(defconst yas/simple-mirror-regexp576"$\\([0-9]+\\)"577"A regexp to recognize a simple mirror.")578579(defvar yas/snippet-id-seed 0580"Contains the next id for a snippet.")581582(defun yas/snippet-next-id ()583(let ((id yas/snippet-id-seed))584(incf yas/snippet-id-seed)585id))586587588;;; Minor mode stuff589590;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX591(defvar last-buffer-undo-list nil)592593(defvar yas/minor-mode-menu nil594"Holds the YASnippet menu")595596(defun yas/init-minor-keymap ()597(let ((map (make-sparse-keymap)))598(easy-menu-define yas/minor-mode-menu599map600"Menu used when YAS/minor-mode is active."601'("YASnippet"602"----"603["Expand trigger" yas/expand604:help "Possibly expand tab trigger before point"]605["Insert at point..." yas/insert-snippet606:help "Prompt for an expandable snippet and expand it at point"]607["New snippet..." yas/new-snippet608:help "Create a new snippet in an appropriate directory"]609["Visit snippet file..." yas/visit-snippet-file610:help "Prompt for an expandable snippet and find its file"]611["Find snippets..." yas/find-snippets612:help "Invoke `find-file' in the appropriate snippet directory"]613"----"614("Snippet menu behaviour"615["Visit snippets" (setq yas/visit-from-menu t)616:help "Visit snippets from the menu"617:active t :style radio :selected yas/visit-from-menu]618["Expand snippets" (setq yas/visit-from-menu nil)619:help "Expand snippets from the menu"620:active t :style radio :selected (not yas/visit-from-menu)]621"----"622["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)623:help "Show snippet submenus for modes that appear to be real major modes"624:active t :style radio :selected (eq yas/use-menu 'real-modes)]625["Show all modes" (setq yas/use-menu 't)626:help "Show one snippet submenu for each loaded table"627:active t :style radio :selected (eq yas/use-menu 't)]628["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)629:help "Show only snippet submenus for the current active modes"630:active t :style radio :selected (eq yas/use-menu 'abbreviate)])631("Indenting"632["Auto" (setq yas/indent-line 'auto)633:help "Indent each line of the snippet with `indent-according-to-mode'"634:active t :style radio :selected (eq yas/indent-line 'auto)]635["Fixed" (setq yas/indent-line 'fixed)636:help "Indent the snippet to the current column"637:active t :style radio :selected (eq yas/indent-line 'fixed)]638["None" (setq yas/indent-line 'none)639:help "Don't apply any particular snippet indentation after expansion"640:active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]641"----"642["Also auto indent first line" (setq yas/also-auto-indent-first-line643(not yas/also-auto-indent-first-line))644:help "When auto-indenting also, auto indent the first line menu"645:active (eq yas/indent-line 'auto)646:style toggle :selected yas/also-auto-indent-first-line]647)648("Prompting method"649["System X-widget" (setq yas/prompt-functions650(cons 'yas/x-prompt651(remove 'yas/x-prompt652yas/prompt-functions)))653:help "Use your windowing system's (gtk, mac, windows, etc...) default menu"654:active t :style radio :selected (eq (car yas/prompt-functions)655'yas/x-prompt)]656["Dropdown-list" (setq yas/prompt-functions657(cons 'yas/dropdown-prompt658(remove 'yas/dropdown-prompt659yas/prompt-functions)))660:help "Use a special dropdown list"661:active t :style radio :selected (eq (car yas/prompt-functions)662'yas/dropdown-prompt)]663["Ido" (setq yas/prompt-functions664(cons 'yas/ido-prompt665(remove 'yas/ido-prompt666yas/prompt-functions)))667:help "Use an ido-style minibuffer prompt"668:active t :style radio :selected (eq (car yas/prompt-functions)669'yas/ido-prompt)]670["Completing read" (setq yas/prompt-functions671(cons 'yas/completing-prompt672(remove 'yas/completing-prompt-prompt673yas/prompt-functions)))674:help "Use a normal minibuffer prompt"675:active t :style radio :selected (eq (car yas/prompt-functions)676'yas/completing-prompt-prompt)]677)678("Misc"679["Wrap region in exit marker"680(setq yas/wrap-around-region681(not yas/wrap-around-region))682:help "If non-nil automatically wrap the selected text in the $0 snippet exit"683:style toggle :selected yas/wrap-around-region]684["Allow stacked expansions "685(setq yas/triggers-in-field686(not yas/triggers-in-field))687:help "If non-nil allow snippets to be triggered inside other snippet fields"688:style toggle :selected yas/triggers-in-field]689["Revive snippets on undo "690(setq yas/snippet-revival691(not yas/snippet-revival))692:help "If non-nil allow snippets to become active again after undo"693:style toggle :selected yas/snippet-revival]694["Good grace "695(setq yas/good-grace696(not yas/good-grace))697:help "If non-nil don't raise errors in bad embedded eslip in snippets"698:style toggle :selected yas/good-grace]699["Ignore filenames as triggers"700(setq yas/ignore-filenames-as-triggers701(not yas/ignore-filenames-as-triggers))702:help "If non-nil don't derive tab triggers from filenames"703:style toggle :selected yas/ignore-filenames-as-triggers]704)705"----"706["Load snippets..." yas/load-directory707:help "Load snippets from a specific directory"]708["Reload everything" yas/reload-all709:help "Cleanup stuff, reload snippets, rebuild menus"]710["About" yas/about711:help "Display some information about YASsnippet"]))712;; Now for the stuff that has direct keybindings713;;714(define-key map "\C-c&\C-s" 'yas/insert-snippet)715(define-key map "\C-c&\C-n" 'yas/new-snippet)716(define-key map "\C-c&\C-v" 'yas/visit-snippet-file)717(define-key map "\C-c&\C-f" 'yas/find-snippets)718map))719720(defvar yas/minor-mode-map (yas/init-minor-keymap)721"The keymap used when `yas/minor-mode' is active.")722723(defun yas/trigger-key-reload (&optional unbind-key)724"Rebind `yas/expand' to the new value of `yas/trigger-key'.725726With optional UNBIND-KEY, try to unbind that key from727`yas/minor-mode-map'."728(when (and unbind-key729(stringp unbind-key)730(not (string= unbind-key "")))731(define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))732(when (and yas/trigger-key733(stringp yas/trigger-key)734(not (string= yas/trigger-key "")))735(define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))736737(defvar yas/tables (make-hash-table)738"A hash table of MAJOR-MODE symbols to `yas/table' objects.")739740(defvar yas/direct-keymaps (list)741"Keymap alist supporting direct snippet keybindings.742743This variable is is placed `emulation-mode-map-alists'.744745Its elements looks like (TABLE-NAME . KEYMAP) and are746calculated when loading snippets. TABLE-NAME is a variable747set buffer-locally when entering `yas/minor-mode'. KEYMAP binds748all defined direct keybindings to the command749`yas/expand-from-keymap', which acts similarly to `yas/expand'")750751(defun yas/direct-keymaps-reload ()752"Force reload the direct keybinding for active snippet tables."753(interactive)754(setq yas/direct-keymaps nil)755(maphash #'(lambda (name table)756(mapc #'(lambda (table)757(push (cons (intern (format "yas//direct-%s" name))758(yas/table-direct-keymap table))759yas/direct-keymaps))760(cons table (yas/table-get-all-parents table))))761yas/tables))762763(defun yas/direct-keymaps-set-vars ()764(let ((modes-to-activate (list major-mode))765(mode major-mode))766(while (setq mode (get mode 'derived-mode-parent))767(push mode modes-to-activate))768(dolist (mode (yas/extra-modes))769(push mode modes-to-activate))770(dolist (mode modes-to-activate)771(let ((name (intern (format "yas//direct-%s" mode))))772(set-default name nil)773(set (make-local-variable name) t)))))774775(defvar yas/minor-mode-hook nil776"Hook run when yas/minor-mode is turned on")777778;;;###autoload779(define-minor-mode yas/minor-mode780"Toggle YASnippet mode.781782When YASnippet mode is enabled, the `tas/trigger-key' key expands783snippets of code depending on the mode.784785With no argument, this command toggles the mode.786positive prefix argument turns on the mode.787Negative prefix argument turns off the mode.788789You can customize the key through `yas/trigger-key'.790791Key bindings:792\\{yas/minor-mode-map}"793nil794;; The indicator for the mode line.795" yas"796:group 'yasnippet797(cond (yas/minor-mode798;; Reload the trigger key799;;800(yas/trigger-key-reload)801;; Load all snippets definitions unless we still don't have a802;; root-directory or some snippets have already been loaded.803;;804(unless (or (null yas/snippet-dirs)805(> (hash-table-count yas/tables) 0))806(yas/reload-all))807;; Install the direct keymaps in `emulation-mode-map-alists'808;; (we use `add-hook' even though it's not technically a hook,809;; but it works). Then define variables named after modes to810;; index `yas/direct-keymaps'.811;;812(add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)813(add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))814(t815;; Uninstall the direct keymaps.816;;817(remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))818819(defun yas/direct-keymaps-set-vars-runonce ()820(yas/direct-keymaps-set-vars)821(remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))822823(defvar yas/dont-activate #'(lambda ()824(and yas/snippet-dirs825(null (yas/get-snippet-tables))))826"If non-nil don't let `yas/minor-mode-on' active yas for this buffer.827828`yas/minor-mode-on' is usually called by `yas/global-mode' so829this effectively lets you define exceptions to the \"global\"830behaviour.")831(make-variable-buffer-local 'yas/dont-activate)832833(defun yas/minor-mode-on ()834"Turn on YASnippet minor mode.835836Do this unless `yas/dont-activate' is t or the function837`yas/get-snippet-tables' (which see), returns an empty list."838(interactive)839(unless (or (and (functionp yas/dont-activate)840(funcall yas/dont-activate))841(and (not (functionp yas/dont-activate))842yas/dont-activate))843(yas/minor-mode 1)))844845(defun yas/minor-mode-off ()846"Turn off YASnippet minor mode."847(interactive)848(yas/minor-mode -1))849850(define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on851:group 'yasnippet852:require 'yasnippet)853854;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;855;; Major mode stuff856;;857(defvar yas/font-lock-keywords858(append '(("^#.*$" . font-lock-comment-face))859lisp-font-lock-keywords860lisp-font-lock-keywords-1861lisp-font-lock-keywords-2862'(("$\\([0-9]+\\)"863(0 font-lock-keyword-face)864(1 font-lock-string-face t))865("${\\([0-9]+\\):?"866(0 font-lock-keyword-face)867(1 font-lock-warning-face t))868("${" font-lock-keyword-face)869("$[0-9]+?" font-lock-preprocessor-face)870("\\(\\$(\\)" 1 font-lock-preprocessor-face)871("}"872(0 font-lock-keyword-face)))))873874(defun yas/init-major-keymap ()875(let ((map (make-sparse-keymap)))876(easy-menu-define nil877map878"Menu used when snippet-mode is active."879(cons "Snippet"880(mapcar #'(lambda (ent)881(when (third ent)882(define-key map (third ent) (second ent)))883(vector (first ent) (second ent) t))884(list885(list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")886(list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))887map))888889(defvar snippet-mode-map890(yas/init-major-keymap)891"The keymap used when `snippet-mode' is active")892893894(define-derived-mode snippet-mode text-mode "Snippet"895"A mode for editing yasnippets"896(set-syntax-table (standard-syntax-table))897(setq font-lock-defaults '(yas/font-lock-keywords))898(set (make-local-variable 'require-final-newline) nil)899(use-local-map snippet-mode-map))900901902903;;; Internal structs for template management904905(defstruct (yas/template (:constructor yas/make-blank-template))906"A template for a snippet."907table908key909content910name911condition912expand-env913file914keybinding915uuid916menu-binding-pair917group ;; as dictated by the #group: directive or .yas-make-groups918perm-group ;; as dictated by `yas/define-menu'919)920921(defun yas/populate-template (template &rest args)922"Helper function to populate a template with properties"923(let (p v)924(while args925(aset template926(position (intern (substring (symbol-name (car args)) 1))927(mapcar #'car (get 'yas/template 'cl-struct-slots)))928(second args))929(setq args (cddr args)))930template))931932(defstruct (yas/table (:constructor yas/make-snippet-table (name)))933"A table to store snippets for a particular mode.934935Has the following fields:936937`yas/table-name'938939A symbol name normally corresponding to a major mode, but can940also be a pseudo major-mode to be referenced in941`yas/extra-modes', for example.942943`yas/table-hash'944945A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is946a string or a vector, where the former is the snippet's trigger947and the latter means it's a direct keybinding. NAMEHASH is yet948another hash of (NAME . TEMPLATE) where NAME is the snippet's949name and TEMPLATE is a `yas/template' object.950951`yas/table-parents'952953A list of tables considered parents of this table: i.e. when954searching for expansions they are searched as well.955956`yas/table-direct-keymap'957958A keymap for the snippets in this table that have direct959keybindings. This is kept in sync with the keyhash, i.e., all960the elements of the keyhash that are vectors appear here as961bindings to `yas/expand-from-keymap'.962963`yas/table-uuidhash'964965A hash table mapping snippets uuid's to the same `yas/template'966objects. A snippet uuid defaults to the snippet's name.967"968name969(hash (make-hash-table :test 'equal))970(uuidhash (make-hash-table :test 'equal))971(parents nil)972(direct-keymap (make-sparse-keymap)))973974(defun yas/get-template-by-uuid (mode uuid)975"Find the snippet template in MODE by its UUID."976(let* ((table (gethash mode yas/tables mode)))977(when table978(gethash uuid (yas/table-uuidhash table)))))979980;; Apropos storing/updating, this works with two steps:981;;982;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by983;; snippet uuid984;;985;; 2. `yas/add-template' to add the mappings again:986;;987;; Create or index the entry in TABLES's `yas/table-hash'988;; linking KEY to a namehash. That namehash links NAME to989;; TEMPLATE, and is also created a new namehash inside that990;; entry.991;;992(defun yas/remove-template-by-uuid (table uuid)993"Remove from TABLE a template identified by UUID."994(let ((template (gethash uuid (yas/table-uuidhash table))))995(when template996(let* ((name (yas/template-name template))997(empty-keys nil))998;; Remove the name from each of the targeted namehashes999;;1000(maphash #'(lambda (k v)1001(let ((template (gethash name v)))1002(when (and template1003(eq uuid (yas/template-uuid template)))1004(remhash name v)1005(when (zerop (hash-table-count v))1006(push k empty-keys)))))1007(yas/table-hash table))1008;; Remove the namehashed themselves if they've become empty1009;;1010(dolist (key empty-keys)1011(remhash key (yas/table-hash table)))10121013;; Finally, remove the uuid from the uuidhash1014;;1015(remhash uuid (yas/table-uuidhash table))))))101610171018(defun yas/add-template (table template)1019"Store in TABLE the snippet template TEMPLATE.10201021KEY can be a string (trigger key) of a vector (direct1022keybinding)."1023(let ((name (yas/template-name template))1024(key (yas/template-key template))1025(keybinding (yas/template-keybinding template))1026(menu-binding (car (yas/template-menu-binding-pair template))))1027(dolist (k (remove nil (list key keybinding)))1028(puthash name1029template1030(or (gethash k1031(yas/table-hash table))1032(puthash k1033(make-hash-table :test 'equal)1034(yas/table-hash table))))1035(when (vectorp k)1036(define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))10371038(when menu-binding1039(setf (getf (cdr menu-binding) :keys)1040(or (and keybinding (key-description keybinding))1041(and key (concat key yas/trigger-symbol))))1042(setcar (cdr menu-binding)1043name))10441045(puthash (yas/template-uuid template) template (yas/table-uuidhash table))))10461047(defun yas/update-template (snippet-table template)1048"Add or update TEMPLATE in SNIPPET-TABLE.10491050Also takes care of adding and updaring to the associated menu."1051;; Remove from table by uuid1052;;1053(yas/remove-template-by-uuid snippet-table (yas/template-uuid template))1054;; Add to table again1055;;1056(yas/add-template snippet-table template)1057;; Take care of the menu1058;;1059(let ((keymap (yas/menu-keymap-get-create snippet-table))1060(group (yas/template-group template)))1061(when (and yas/use-menu1062keymap1063(not (cdr (yas/template-menu-binding-pair template))))1064;; Remove from menu keymap1065;;1066(yas/delete-from-keymap keymap (yas/template-uuid template))10671068;; Add necessary subgroups as necessary.1069;;1070(dolist (subgroup group)1071(let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))1072(unless (and subgroup-keymap1073(keymapp subgroup-keymap))1074(setq subgroup-keymap (make-sparse-keymap))1075(define-key keymap (vector (make-symbol subgroup))1076`(menu-item ,subgroup ,subgroup-keymap)))1077(setq keymap subgroup-keymap)))10781079;; Add this entry to the keymap1080;;1081(let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))1082(define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))10831084(defun yas/fetch (table key)1085"Fetch templates in TABLE by KEY.10861087Return a list of cons (NAME . TEMPLATE) where NAME is a1088string and TEMPLATE is a `yas/template' structure."1089(let* ((keyhash (yas/table-hash table))1090(namehash (and keyhash (gethash key keyhash))))1091(when namehash1092(yas/filter-templates-by-condition1093(let (alist)1094(maphash #'(lambda (k v)1095(push (cons k v) alist))1096namehash)1097alist)))))109810991100;;; Filtering/condition logic11011102(defun yas/eval-condition (condition)1103(condition-case err1104(save-excursion1105(save-restriction1106(save-match-data1107(eval condition))))1108(error (progn1109(message (format "[yas] error in condition evaluation: %s"1110(error-message-string err)))1111nil))))111211131114(defun yas/filter-templates-by-condition (templates)1115"Filter the templates using the applicable condition.11161117TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a1118string and TEMPLATE is a `yas/template' structure.11191120This function implements the rules described in1121`yas/buffer-local-condition'. See that variables documentation."1122(let ((requirement (yas/require-template-specific-condition-p)))1123(if (eq requirement 'always)1124templates1125(remove-if-not #'(lambda (pair)1126(yas/template-can-expand-p1127(yas/template-condition (cdr pair)) requirement))1128templates))))11291130(defun yas/require-template-specific-condition-p ()1131"Decides if this buffer requests/requires snippet-specific1132conditions to filter out potential expansions."1133(if (eq 'always yas/buffer-local-condition)1134'always1135(let ((local-condition (or (and (consp yas/buffer-local-condition)1136(yas/eval-condition yas/buffer-local-condition))1137yas/buffer-local-condition)))1138(when local-condition1139(if (eq local-condition t)1140t1141(and (consp local-condition)1142(eq 'require-snippet-condition (car local-condition))1143(symbolp (cdr local-condition))1144(cdr local-condition)))))))11451146(defun yas/template-can-expand-p (condition requirement)1147"Evaluates CONDITION and REQUIREMENT and returns a boolean"1148(let* ((result (or (null condition)1149(yas/eval-condition condition))))1150(cond ((eq requirement t)1151result)1152(t1153(eq requirement result)))))11541155(defun yas/table-get-all-parents (table)1156"Returns a list of all parent tables of TABLE"1157(let ((parents (yas/table-parents table)))1158(when parents1159(append (copy-list parents)1160(mapcan #'yas/table-get-all-parents parents)))))11611162(defun yas/table-templates (table)1163(when table1164(let ((acc (list)))1165(maphash #'(lambda (key namehash)1166(maphash #'(lambda (name template)1167(push (cons name template) acc))1168namehash))1169(yas/table-hash table))1170(yas/filter-templates-by-condition acc))))11711172(defun yas/current-key ()1173"Get the key under current position. A key is used to find1174the template of a snippet in the current snippet-table."1175(let ((start (point))1176(end (point))1177(syntaxes yas/key-syntaxes)1178syntax1179done1180templates)1181(while (and (not done) syntaxes)1182(setq syntax (car syntaxes))1183(setq syntaxes (cdr syntaxes))1184(save-excursion1185(skip-syntax-backward syntax)1186(setq start (point)))1187(setq templates1188(mapcan #'(lambda (table)1189(yas/fetch table (buffer-substring-no-properties start end)))1190(yas/get-snippet-tables)))1191(if templates1192(setq done t)1193(setq start end)))1194(list templates1195start1196end)))119711981199(defun yas/table-all-keys (table)1200(when table1201(let ((acc))1202(maphash #'(lambda (key templates)1203(when (yas/filter-templates-by-condition templates)1204(push key acc)))1205(yas/table-hash table))1206acc)))120712081209;;; Internal functions12101211(defun yas/real-mode? (mode)1212"Try to find out if MODE is a real mode. The MODE bound to1213a function (like `c-mode') is considered real mode. Other well1214known mode like `ruby-mode' which is not part of Emacs might1215not bound to a function until it is loaded. So yasnippet keeps1216a list of modes like this to help the judgement."1217(or (fboundp mode)1218(find mode yas/known-modes)))12191220(defun yas/eval-lisp (form)1221"Evaluate FORM and convert the result to string."1222(let ((retval (catch 'yas/exception1223(condition-case err1224(save-excursion1225(save-restriction1226(save-match-data1227(widen)1228(let ((result (eval form)))1229(when result1230(format "%s" result))))))1231(error (if yas/good-grace1232(format "[yas] elisp error! %s" (error-message-string err))1233(error (format "[yas] elisp error: %s"1234(error-message-string err)))))))))1235(when (and (consp retval)1236(eq 'yas/exception (car retval)))1237(error (cdr retval)))1238retval))12391240(defun yas/eval-lisp-no-saves (form)1241(condition-case err1242(eval form)1243(error (if yas/good-grace1244(format "[yas] elisp error! %s" (error-message-string err))1245(error (format "[yas] elisp error: %s"1246(error-message-string err)))))))12471248(defun yas/read-lisp (string &optional nil-on-error)1249"Read STRING as a elisp expression and return it.12501251In case STRING in an invalid expression and NIL-ON-ERROR is nil,1252return an expression that when evaluated will issue an error."1253(condition-case err1254(read string)1255(error (and (not nil-on-error)1256`(error (error-message-string err))))))12571258(defun yas/read-keybinding (keybinding)1259"Read KEYBINDING as a snippet keybinding, return a vector."1260(when (and keybinding1261(not (string-match "keybinding" keybinding)))1262(condition-case err1263(let ((keybinding-string (or (and (string-match "\".*\"" keybinding)1264(read keybinding))1265;; "KEY-DESC" with quotes is deprecated..., but supported1266keybinding)))1267(read-kbd-macro keybinding-string 'need-vector))1268(error1269(message "[yas] warning: keybinding \"%s\" invalid since %s."1270keybinding (error-message-string err))1271nil))))12721273(defvar yas/extra-modes nil1274"If non-nil, also lookup snippets for this/these modes.12751276Can be a symbol or a list of symbols.12771278This variable probably makes more sense as buffer-local, so1279ensure your use `make-local-variable' when you set it.")1280(defun yas/extra-modes ()1281(if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))1282(defvaralias 'yas/mode-symbol 'yas/extra-modes)12831284(defun yas/table-get-create (mode)1285"Get the snippet table corresponding to MODE.12861287Optional DIRECTORY gets recorded as the default directory to1288search for snippet files if the retrieved/created table didn't1289already have such a property."1290(let ((table (gethash mode1291yas/tables)))1292(unless table1293(setq table (yas/make-snippet-table (symbol-name mode)))1294(puthash mode table yas/tables)1295(aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))1296(yas/table-direct-keymap table)))1297table))12981299(defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)1300"Get snippet tables for current buffer.13011302Return a list of 'yas/table' objects indexed by mode.13031304The modes are tried in this order: optional MODE-SYMBOL, then1305`yas/extra-modes', then `major-mode' then, unless1306DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either1307MODE-SYMBOL or `major-mode'.13081309Guessing is done by looking up the MODE-SYMBOL's1310`derived-mode-parent' property, see also `derived-mode-p'."1311(let ((mode-tables1312(remove nil1313(mapcar #'(lambda (mode)1314(gethash mode yas/tables))1315(remove nil (append (list mode-symbol)1316(yas/extra-modes)1317(list major-mode1318(and (not dont-search-parents)1319(get major-mode1320'derived-mode-parent)))))))))1321(remove-duplicates1322(append mode-tables1323(mapcan #'yas/table-get-all-parents mode-tables)))))13241325(defun yas/menu-keymap-get-create (table)1326"Get or create the main menu keymap correspondong to MODE.13271328This may very well create a plethora of menu keymaps and arrange1329them in all `yas/menu-table'"1330(let* ((mode (intern (yas/table-name table)))1331(menu-keymap (or (gethash mode yas/menu-table)1332(puthash mode (make-sparse-keymap) yas/menu-table)))1333(parents (yas/table-parents table)))1334(mapc #'yas/menu-keymap-get-create parents)1335(define-key yas/minor-mode-menu (vector mode)1336`(menu-item ,(symbol-name mode) ,menu-keymap1337:visible (yas/show-menu-p ',mode)))1338menu-keymap))13391340;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1341;;; Template-related and snippet loading functions13421343(defun yas/parse-template (&optional file)1344"Parse the template in the current buffer.13451346Optional FILE is the absolute file name of the file being1347parsed.13481349Optional GROUP is the group where the template is to go,1350otherwise we attempt to calculate it from FILE.13511352Return a snippet-definition, i.e. a list13531354(KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)13551356If the buffer contains a line of \"# --\" then the contents above1357this line are ignored. Directives can set most of these with the syntax:13581359# directive-name : directive-value13601361Here's a list of currently recognized directives:13621363* type1364* name1365* contributor1366* condition1367* group1368* key1369* expand-env1370* binding1371* uuid"1372(goto-char (point-min))1373(let* ((type 'snippet)1374(name (and file1375(file-name-nondirectory file)))1376(key (unless yas/ignore-filenames-as-triggers1377(and name1378(file-name-sans-extension name))))1379template1380bound1381condition1382(group (and file1383(yas/calculate-group file)))1384expand-env1385binding1386uuid)1387(if (re-search-forward "^# --\n" nil t)1388(progn (setq template1389(buffer-substring-no-properties (point)1390(point-max)))1391(setq bound (point))1392(goto-char (point-min))1393(while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)1394(when (string= "uuid" (match-string-no-properties 1))1395(setq uuid (match-string-no-properties 2)))1396(when (string= "type" (match-string-no-properties 1))1397(setq type (if (string= "command" (match-string-no-properties 2))1398'command1399'snippet)))1400(when (string= "key" (match-string-no-properties 1))1401(setq key (match-string-no-properties 2)))1402(when (string= "name" (match-string-no-properties 1))1403(setq name (match-string-no-properties 2)))1404(when (string= "condition" (match-string-no-properties 1))1405(setq condition (yas/read-lisp (match-string-no-properties 2))))1406(when (string= "group" (match-string-no-properties 1))1407(setq group (match-string-no-properties 2)))1408(when (string= "expand-env" (match-string-no-properties 1))1409(setq expand-env (yas/read-lisp (match-string-no-properties 2)1410'nil-on-error)))1411(when (string= "binding" (match-string-no-properties 1))1412(setq binding (match-string-no-properties 2)))))1413(setq template1414(buffer-substring-no-properties (point-min) (point-max))))1415(when (eq type 'command)1416(setq template (yas/read-lisp (concat "(progn" template ")"))))1417(when group1418(setq group (split-string group "\\.")))1419(list key template name condition group expand-env file binding uuid)))14201421(defun yas/calculate-group (file)1422"Calculate the group for snippet file path FILE."1423(let* ((dominating-dir (locate-dominating-file file1424".yas-make-groups"))1425(extra-path (and dominating-dir1426(replace-regexp-in-string (concat "^"1427(expand-file-name dominating-dir))1428""1429(expand-file-name file))))1430(extra-dir (and extra-path1431(file-name-directory extra-path)))1432(group (and extra-dir1433(replace-regexp-in-string "/"1434"."1435(directory-file-name extra-dir)))))1436group))14371438(defun yas/subdirs (directory &optional file?)1439"Return subdirs or files of DIRECTORY according to FILE?."1440(remove-if (lambda (file)1441(or (string-match "^\\."1442(file-name-nondirectory file))1443(string-match "^#.*#$"1444(file-name-nondirectory file))1445(string-match "~$"1446(file-name-nondirectory file))1447(if file?1448(file-directory-p file)1449(not (file-directory-p file)))))1450(directory-files directory t)))14511452(defun yas/make-menu-binding (template)1453(let ((mode (intern (yas/table-name (yas/template-table template)))))1454`(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))14551456(defun yas/expand-or-visit-from-menu (mode uuid)1457(let* ((table (yas/table-get-create mode))1458(yas/current-template (and table1459(gethash uuid (yas/table-uuidhash table)))))1460(when yas/current-template1461(if yas/visit-from-menu1462(yas/visit-snippet-file-1 yas/current-template)1463(let ((where (if (region-active-p)1464(cons (region-beginning) (region-end))1465(cons (point) (point)))))1466(yas/expand-snippet (yas/template-content yas/current-template)1467(car where)1468(cdr where)))))))14691470;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1471;; Popping up for keys and templates1472;;1473(defun yas/prompt-for-template (templates &optional prompt)1474"Interactively choose a template from the list TEMPLATES.14751476TEMPLATES is a list of `yas/template'."1477(when templates1478(setq templates1479(sort templates #'(lambda (t1 t2)1480(< (length (yas/template-name t1))1481(length (yas/template-name t2))))))1482(if yas/x-pretty-prompt-templates1483(yas/x-pretty-prompt-templates "Choose a snippet" templates)1484(some #'(lambda (fn)1485(funcall fn (or prompt "Choose a snippet: ")1486templates1487#'yas/template-name))1488yas/prompt-functions))))14891490(defun yas/prompt-for-keys (keys &optional prompt)1491"Interactively choose a template key from the list KEYS."1492(when keys1493(some #'(lambda (fn)1494(funcall fn (or prompt "Choose a snippet key: ") keys))1495yas/prompt-functions)))14961497(defun yas/prompt-for-table (tables &optional prompt)1498(when tables1499(some #'(lambda (fn)1500(funcall fn (or prompt "Choose a snippet table: ")1501tables1502#'yas/table-name))1503yas/prompt-functions)))15041505(defun yas/x-prompt (prompt choices &optional display-fn)1506"Display choices in a x-window prompt."1507;; FIXME: HACK: if we notice that one of the objects in choices is1508;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'1509;;1510;; This would be better implemented by passing CHOICES as a1511;; strucutred tree rather than a list. Modifications would go as far1512;; up as `yas/all-templates' I think.1513;;1514(when (and window-system choices)1515(let ((chosen1516(let (menu d) ;; d for display1517(dolist (c choices)1518(setq d (or (and display-fn (funcall display-fn c))1519c))1520(cond ((stringp d)1521(push (cons (concat " " d) c) menu))1522((listp d)1523(push (car d) menu))))1524(setq menu (list prompt (push "title" menu)))1525(x-popup-menu (if (fboundp 'posn-at-point)1526(let ((x-y (posn-x-y (posn-at-point (point)))))1527(list (list (+ (car x-y) 10)1528(+ (cdr x-y) 20))1529(selected-window)))1530t)1531menu))))1532(or chosen1533(keyboard-quit)))))15341535(defvar yas/x-pretty-prompt-templates nil1536"If non-nil, attempt to prompt for templates like TextMate.")1537(defun yas/x-pretty-prompt-templates (prompt templates)1538"Display TEMPLATES, grouping neatly by table name."1539(let ((pretty-alist (list))1540menu1541more-than-one-table1542prefix)1543(dolist (tl templates)1544(aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))1545(setq more-than-one-table (> (length pretty-alist) 1))1546(setq prefix (if more-than-one-table1547" " ""))1548(dolist (table-and-templates pretty-alist)1549(when (cdr table-and-templates)1550(if more-than-one-table1551(push (yas/table-name (car table-and-templates)) menu))1552(dolist (template (cdr table-and-templates))1553(push (cons (concat prefix (yas/template-name template))1554template) menu))))1555(setq menu (nreverse menu))1556(or (x-popup-menu (if (fboundp 'posn-at-point)1557(let ((x-y (posn-x-y (posn-at-point (point)))))1558(list (list (+ (car x-y) 10)1559(+ (cdr x-y) 20))1560(selected-window)))1561t)1562(list prompt (push "title" menu)))1563(keyboard-quit))))15641565(defun yas/ido-prompt (prompt choices &optional display-fn)1566(when (and (featurep 'ido)1567ido-mode)1568(yas/completing-prompt prompt choices display-fn #'ido-completing-read)))15691570(eval-when-compile (require 'dropdown-list nil t))1571(defun yas/dropdown-prompt (prompt choices &optional display-fn)1572(when (featurep 'dropdown-list)1573(let (formatted-choices1574filtered-choices1575d1576n)1577(dolist (choice choices)1578(setq d (or (and display-fn (funcall display-fn choice))1579choice))1580(when (stringp d)1581(push d formatted-choices)1582(push choice filtered-choices)))15831584(setq n (and formatted-choices (dropdown-list formatted-choices)))1585(if n1586(nth n filtered-choices)1587(keyboard-quit)))))15881589(defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)1590(let (formatted-choices1591filtered-choices1592chosen1593d1594(completion-fn (or completion-fn1595#'completing-read)))1596(dolist (choice choices)1597(setq d (or (and display-fn (funcall display-fn choice))1598choice))1599(when (stringp d)1600(push d formatted-choices)1601(push choice filtered-choices)))1602(setq chosen (and formatted-choices1603(funcall completion-fn prompt1604formatted-choices1605nil1606'require-match1607nil1608nil)))1609(when chosen1610(nth (position chosen formatted-choices :test #'string=) filtered-choices))))16111612(defun yas/no-prompt (prompt choices &optional display-fn)1613(first choices))16141615;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1616;; Loading snippets from files1617;;1618(defun yas/load-directory-1 (directory &optional mode-sym parents)1619"Recursively load snippet templates from DIRECTORY."16201621;; Load .yas-setup.el files wherever we find them1622;;1623(let ((file (concat directory "/" ".yas-setup")))1624(when (or (file-readable-p (concat file ".el"))1625(file-readable-p (concat file ".elc")))1626(load file)))16271628;;1629;;1630(unless (file-exists-p (concat directory "/" ".yas-skip"))1631(let* ((major-mode-and-parents (if mode-sym1632(cons mode-sym parents)1633(yas/compute-major-mode-and-parents (concat directory1634"/dummy"))))1635(yas/ignore-filenames-as-triggers1636(or yas/ignore-filenames-as-triggers1637(file-exists-p (concat directory "/"1638".yas-ignore-filenames-as-triggers"))))1639(snippet-defs nil))1640;; load the snippet files1641;;1642(with-temp-buffer1643(dolist (file (yas/subdirs directory 'no-subdirs-just-files))1644(when (file-readable-p file)1645(insert-file-contents file nil nil nil t)1646(push (yas/parse-template file)1647snippet-defs))))1648(when snippet-defs1649(yas/define-snippets (car major-mode-and-parents)1650snippet-defs1651(cdr major-mode-and-parents)))1652;; now recurse to a lower level1653;;1654(dolist (subdir (yas/subdirs directory))1655(yas/load-directory-1 subdir1656(car major-mode-and-parents)1657(cdr major-mode-and-parents))))))16581659(defun yas/load-directory (directory)1660"Load snippet definition from a directory hierarchy.16611662Below the top-level directory, each directory is a mode1663name. And under each subdirectory, each file is a definition1664of a snippet. The file name is the trigger key and the1665content of the file is the template."1666(interactive "DSelect the root directory: ")1667(unless (file-directory-p directory)1668(error "Error %s not a directory" directory))1669(unless yas/snippet-dirs1670(setq yas/snippet-dirs directory))1671(dolist (dir (yas/subdirs directory))1672(yas/load-directory-1 dir))1673(when (interactive-p)1674(message "[yas] Loaded snippets from %s." directory)))16751676(defun yas/load-snippet-dirs ()1677"Reload the directories listed in `yas/snippet-dirs' or1678prompt the user to select one."1679(if yas/snippet-dirs1680(dolist (directory (reverse (yas/snippet-dirs)))1681(yas/load-directory directory))1682(call-interactively 'yas/load-directory)))16831684(defun yas/reload-all (&optional reset-root-directory)1685"Reload all snippets and rebuild the YASnippet menu. "1686(interactive "P")1687;; Turn off global modes and minor modes, save their state though1688;;1689(let ((restore-global-mode (prog1 yas/global-mode1690(yas/global-mode -1)))1691(restore-minor-mode (prog1 yas/minor-mode1692(yas/minor-mode -1))))1693;; Empty all snippet tables and all menu tables1694;;1695(setq yas/tables (make-hash-table))1696(setq yas/menu-table (make-hash-table))16971698;; Init the `yas/minor-mode-map', taking care not to break the1699;; menu....1700;;1701(setf (cdr yas/minor-mode-map)1702(cdr (yas/init-minor-keymap)))17031704(when reset-root-directory1705(setq yas/snippet-dirs nil))17061707;; Reload the directories listed in `yas/snippet-dirs' or prompt1708;; the user to select one.1709;;1710(yas/load-snippet-dirs)1711;; Reload the direct keybindings1712;;1713(yas/direct-keymaps-reload)1714;; Restore the mode configuration1715;;1716(when restore-minor-mode1717(yas/minor-mode 1))1718(when restore-global-mode1719(yas/global-mode 1))17201721(message "[yas] Reloading everything... Done.")))17221723(defun yas/quote-string (string)1724"Escape and quote STRING.1725foo\"bar\\! -> \"foo\\\"bar\\\\!\""1726(concat "\""1727(replace-regexp-in-string "[\\\"]"1728"\\\\\\&"1729string1730t)1731"\""))1732;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1733;;; Yasnippet Bundle17341735(defun yas/initialize ()1736"For backward compatibility, enable `yas/minor-mode' globally"1737(yas/global-mode 1))17381739(defun yas/compile-bundle1740(&optional yasnippet yasnippet-bundle snippet-roots code dropdown)1741"Compile snippets in SNIPPET-ROOTS to a single bundle file.17421743YASNIPPET is the yasnippet.el file path.17441745YASNIPPET-BUNDLE is the output file of the compile result.17461747SNIPPET-ROOTS is a list of root directories that contains the1748snippets definition.17491750CODE is the code to be placed at the end of the generated file1751and that can initialize the YASnippet bundle.17521753Last optional argument DROPDOWN is the filename of the1754dropdown-list.el library.17551756Here's the default value for all the parameters:17571758(yas/compile-bundle \"yasnippet.el\"1759\"yasnippet-bundle.el\"1760\"snippets\")1761\"(yas/initialize-bundle)1762### autoload1763(require 'yasnippet-bundle)`\"1764\"dropdown-list.el\")1765"1766(interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "1767"\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))17681769(let* ((yasnippet (or yasnippet1770"yasnippet.el"))1771(yasnippet-bundle (or yasnippet-bundle1772"./yasnippet-bundle.el"))1773(snippet-roots (or snippet-roots1774"snippets"))1775(dropdown (or dropdown1776"dropdown-list.el"))1777(code (or (and code1778(condition-case err (read code) (error nil))1779code)1780(concat "(yas/initialize-bundle)"1781"\n;;;###autoload" ; break through so that won't1782"(require 'yasnippet-bundle)")))1783(dirs (or (and (listp snippet-roots) snippet-roots)1784(list snippet-roots)))1785(bundle-buffer nil))1786(with-temp-file yasnippet-bundle1787(insert ";;; yasnippet-bundle.el --- "1788"Yet another snippet extension (Auto compiled bundle)\n")1789(insert-file-contents yasnippet)1790(goto-char (point-max))1791(insert "\n")1792(when dropdown1793(insert-file-contents dropdown))1794(goto-char (point-max))1795(insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")1796(insert ";;;; Auto-generated code ;;;;\n")1797(insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")1798(insert "(defun yas/initialize-bundle ()\n"1799" \"Initialize YASnippet and load snippets in the bundle.\"")1800(flet ((yas/define-snippets1801(mode snippets &optional parent-or-parents)1802(insert ";;; snippets for " (symbol-name mode) "\n")1803(let ((literal-snippets (list)))1804(dolist (snippet snippets)1805(let ((key (first snippet))1806(template-content (second snippet))1807(name (third snippet))1808(condition (fourth snippet))1809(group (fifth snippet))1810(expand-env (sixth snippet))1811(file nil) ;; (seventh snippet)) ;; omit on purpose1812(binding (eighth snippet))1813(uuid (ninth snippet)))1814(push `(,key1815,template-content1816,name1817,condition1818,group1819,expand-env1820,file1821,binding1822,uuid)1823literal-snippets)))1824(insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))1825(insert "\n\n"))))1826(dolist (dir dirs)1827(dolist (subdir (yas/subdirs dir))1828(let ((file (concat subdir "/.yas-setup.el")))1829(when (file-readable-p file)1830(insert ";; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")1831(goto-char (+ (point)1832(second (insert-file-contents file))))))1833(yas/load-directory-1 subdir nil))))18341835(insert (pp-to-string `(yas/global-mode 1)))1836(insert ")\n\n" code "\n")18371838;; bundle-specific provide and value for yas/dont-activate1839(let ((bundle-feature-name (file-name-nondirectory1840(file-name-sans-extension1841yasnippet-bundle))))1842(insert (pp-to-string `(set-default 'yas/dont-activate1843#'(lambda ()1844(and (or yas/snippet-dirs1845(featurep ',(make-symbol bundle-feature-name)))1846(null (yas/get-snippet-tables)))))))1847(insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))18481849(insert ";;; "1850(file-name-nondirectory yasnippet-bundle)1851" ends here\n"))))18521853(defun yas/compile-textmate-bundle ()1854(interactive)1855(yas/compile-bundle "yasnippet.el"1856"./yasnippet-textmate-bundle.el"1857"extras/imported/"1858(concat "(yas/initialize-bundle)"1859"\n;;;###autoload" ; break through so that won't1860"(require 'yasnippet-textmate-bundle)")1861"dropdown-list.el"))18621863;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1864;;; Some user level functions1865;;;18661867(defun yas/about ()1868(interactive)1869(message (concat "yasnippet (version "1870yas/version1871") -- pluskid <[email protected]>/joaotavora <[email protected]>")))18721873(defun yas/define-snippets (mode snippets &optional parent-mode)1874"Define SNIPPETS for MODE.18751876SNIPPETS is a list of snippet definitions, each taking the1877following form18781879(KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)18801881Within these, only KEY and TEMPLATE are actually mandatory.18821883TEMPLATE might be a lisp form or a string, depending on whether1884this is a snippet or a snippet-command.18851886CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have1887been `yas/read-lisp'-ed and will eventually be1888`yas/eval-lisp'-ed.18891890The remaining elements are strings.18911892FILE is probably of very little use if you're programatically1893defining snippets.18941895UUID is the snippets \"unique-id\". Loading a second snippet file1896with the same uuid replaced the previous snippet.18971898You can use `yas/parse-template' to return such lists based on1899the current buffers contents.19001901Optional PARENT-MODE can be used to specify the parent tables of1902MODE. It can be a mode symbol of a list of mode symbols. It does1903not need to be a real mode."1904;; X) `snippet-table' is created or retrieved for MODE, same goes1905;; for the list of snippet tables `parent-tables'.1906;;1907(let ((snippet-table (yas/table-get-create mode))1908(parent-tables (mapcar #'yas/table-get-create1909(if (listp parent-mode)1910parent-mode1911(list parent-mode))))1912(template nil))1913;; X) Connect `snippet-table' with `parent-tables'.1914;;1915;; TODO: this should be a remove-duplicates of the concatenation1916;; of `snippet-table's existings parents with the new parents...1917;;1918(dolist (parent parent-tables)1919(unless (find parent (yas/table-parents snippet-table))1920(push parent1921(yas/table-parents snippet-table))))19221923;; X) Now, iterate for evey snippet def list1924;;1925(dolist (snippet snippets)1926(setq template (yas/define-snippets-1 snippet1927snippet-table)))1928template))19291930(defun yas/define-snippets-1 (snippet snippet-table)1931"Helper for `yas/define-snippets'."1932;; X) Calculate some more defaults on the values returned by1933;; `yas/parse-template'.1934;;1935(let* ((file (seventh snippet))1936(key (or (car snippet)1937(unless yas/ignore-filenames-as-triggers1938(and file1939(file-name-sans-extension (file-name-nondirectory file))))))1940(name (or (third snippet)1941(and file1942(file-name-directory file))))1943(condition (fourth snippet))1944(group (fifth snippet))1945(keybinding (yas/read-keybinding (eighth snippet)))1946(uuid (or (ninth snippet)1947name))1948(template (or (gethash uuid (yas/table-uuidhash snippet-table))1949(yas/make-blank-template))))1950;; X) populate the template object1951;;1952(yas/populate-template template1953:table snippet-table1954:key key1955:content (second snippet)1956:name (or name key)1957:group group1958:condition condition1959:expand-env (sixth snippet)1960:file (seventh snippet)1961:keybinding keybinding1962:uuid uuid)1963;; X) Update this template in the appropriate table. This step1964;; also will take care of adding the key indicators in the1965;; templates menu entry, if any1966;;1967(yas/update-template snippet-table template)1968;; X) Return the template1969;;1970;;1971template))19721973(defun yas/snippet-menu-binding-pair-get-create (template &optional type)1974"Get TEMPLATE's menu binding or assign it a new one."1975(or (yas/template-menu-binding-pair template)1976(let ((key (yas/template-key template))1977(keybinding (yas/template-keybinding template)))1978(setf (yas/template-menu-binding-pair template)1979(cons `(menu-item ,(or (yas/template-name template)1980(yas/template-uuid template))1981,(yas/make-menu-binding template)1982:keys ,nil)1983type)))))19841985(defun yas/show-menu-p (mode)1986(cond ((eq yas/use-menu 'abbreviate)1987(find mode1988(mapcar #'(lambda (table)1989(intern (yas/table-name table)))1990(yas/get-snippet-tables))))1991((eq yas/use-menu 'real-modes)1992(yas/real-mode? mode))1993(t1994t)))19951996(defun yas/delete-from-keymap (keymap uuid)1997"Recursively delete items with UUID from KEYMAP and its submenus."19981999;; XXX: This used to skip any submenus named \"parent mode\"2000;;2001;; First of all, recursively enter submenus, i.e. the tree is2002;; searched depth first so that stale submenus can be found in the2003;; higher passes.2004;;2005(mapc #'(lambda (item)2006(when (and (listp (cdr item))2007(keymapp (third (cdr item))))2008(yas/delete-from-keymap (third (cdr item)) uuid)))2009(rest keymap))2010;; Set the uuid entry to nil2011;;2012(define-key keymap (vector (make-symbol uuid)) nil)2013;; Destructively modify keymap2014;;2015(setcdr keymap (delete-if #'(lambda (item)2016(or (null (cdr item))2017(and (keymapp (third (cdr item)))2018(null (cdr (third (cdr item)))))))2019(rest keymap))))20202021(defun yas/define-menu (mode menu omit-items)2022"Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.20232024MENU is a list, its elements can be:20252026- (yas/item UUID) : Creates an entry the snippet identified with2027UUID. The menu entry for a snippet thus identified is2028permanent, i.e. it will never move in the menu.20292030- (yas/separator) : Creates a separator20312032- (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,2033SUBMENU has the same form as MENU. NAME is also added to the2034list of groups of the snippets defined thereafter.20352036OMIT-ITEMS is a list of snippet uuid's that will always be2037ommited from MODE's menu, even if they're manually loaded.2038"2039(let* ((table (yas/table-get-create mode))2040(hash (yas/table-uuidhash table)))2041(yas/define-menu-1 table2042(yas/menu-keymap-get-create table)2043menu2044hash)2045(dolist (uuid omit-items)2046(let ((template (or (gethash uuid hash)2047(yas/populate-template (puthash uuid2048(yas/make-blank-template)2049hash)2050:table table2051:uuid uuid))))2052(setf (yas/template-menu-binding-pair template) (cons nil :none))))))20532054(defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)2055(dolist (e (reverse menu))2056(cond ((eq (first e) 'yas/item)2057(let ((template (or (gethash (second e) uuidhash)2058(yas/populate-template (puthash (second e)2059(yas/make-blank-template)2060uuidhash)2061:table table2062:perm-group group-list2063:uuid (second e)))))2064(define-key keymap (vector (make-symbol (second e)))2065(car (yas/snippet-menu-binding-pair-get-create template :stay)))))2066((eq (first e) 'yas/submenu)2067(let ((subkeymap (make-sparse-keymap)))2068(define-key keymap (vector (make-symbol(second e)))2069`(menu-item ,(second e) ,subkeymap))2070(yas/define-menu-1 table2071subkeymap2072(third e)2073uuidhash2074(append group-list (list (second e))))))2075((eq (first e) 'yas/separator)2076(define-key keymap (vector (gensym))2077'(menu-item "----")))2078(t2079(message "[yas] don't know anything about menu entry %s" (first e))))))20802081(defun yas/define (mode key template &optional name condition group)2082"Define a snippet. Expanding KEY into TEMPLATE.20832084NAME is a description to this template. Also update the menu if2085`yas/use-menu' is `t'. CONDITION is the condition attached to2086this snippet. If you attach a condition to a snippet, then it2087will only be expanded when the condition evaluated to non-nil."2088(yas/define-snippets mode2089(list (list key template name condition group))))20902091(defun yas/hippie-try-expand (first-time?)2092"Integrate with hippie expand. Just put this function in2093`hippie-expand-try-functions-list'."2094(if (not first-time?)2095(let ((yas/fallback-behavior 'return-nil))2096(yas/expand))2097(undo 1)2098nil))209921002101;;; Apropos condition-cache:2102;;;2103;;;2104;;;2105;;;2106(defvar yas/condition-cache-timestamp nil)2107(defmacro yas/define-condition-cache (func doc &rest body)2108"Define a function FUNC with doc DOC and body BODY, BODY is2109executed at most once every snippet expansion attempt, to check2110expansion conditions.21112112It doesn't make any sense to call FUNC programatically."2113`(defun ,func () ,(if (and doc2114(stringp doc))2115(concat doc2116"\n\nFor use in snippets' conditions. Within each2117snippet-expansion routine like `yas/expand', computes actual2118value for the first time then always returns a cached value.")2119(setq body (cons doc body))2120nil)2121(let ((timestamp-and-value (get ',func 'yas/condition-cache)))2122(if (equal (car timestamp-and-value) yas/condition-cache-timestamp)2123(cdr timestamp-and-value)2124(let ((new-value (progn2125,@body2126)))2127(put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))2128new-value)))))21292130(defalias 'yas/expand 'yas/expand-from-trigger-key)2131(defun yas/expand-from-trigger-key (&optional field)2132"Expand a snippet before point.21332134If no snippet expansion is possible, fall back to the behaviour2135defined in `yas/fallback-behavior'.21362137Optional argument FIELD is for non-interactive use and is an2138object satisfying `yas/field-p' to restrict the expansion to."2139(interactive)2140(setq yas/condition-cache-timestamp (current-time))2141(let (templates-and-pos)2142(unless (and yas/expand-only-for-last-commands2143(not (member last-command yas/expand-only-for-last-commands)))2144(setq templates-and-pos (if field2145(save-restriction2146(narrow-to-region (yas/field-start field)2147(yas/field-end field))2148(yas/current-key))2149(yas/current-key))))2150(if (and templates-and-pos2151(first templates-and-pos))2152(yas/expand-or-prompt-for-template (first templates-and-pos)2153(second templates-and-pos)2154(third templates-and-pos))2155(yas/fallback 'trigger-key))))21562157(defun yas/expand-from-keymap ()2158"Directly expand some snippets, searching `yas/direct-keymaps'.21592160If expansion fails, execute the previous binding for this key"2161(interactive)2162(setq yas/condition-cache-timestamp (current-time))2163(let* ((vec (this-command-keys-vector))2164(templates (mapcan #'(lambda (table)2165(yas/fetch table vec))2166(yas/get-snippet-tables))))2167(if templates2168(yas/expand-or-prompt-for-template templates)2169(let ((yas/fallback-behavior 'call-other-command))2170(yas/fallback)))))21712172(defun yas/expand-or-prompt-for-template (templates &optional start end)2173"Expand one of TEMPLATES from START to END.21742175Prompt the user if TEMPLATES has more than one element, else2176expand immediately. Common gateway for2177`yas/expand-from-trigger-key' and `yas/expand-from-keymap'."2178(let ((yas/current-template (or (and (rest templates) ;; more than one2179(yas/prompt-for-template (mapcar #'cdr templates)))2180(cdar templates))))2181(when yas/current-template2182(yas/expand-snippet (yas/template-content yas/current-template)2183start2184end2185(yas/template-expand-env yas/current-template)))))21862187(defun yas/fallback (&optional from-trigger-key-p)2188"Fallback after expansion has failed.21892190Common gateway for `yas/expand-from-trigger-key' and2191`yas/expand-from-keymap'."2192(cond ((eq yas/fallback-behavior 'return-nil)2193;; return nil2194nil)2195((eq yas/fallback-behavior 'call-other-command)2196(let* ((yas/minor-mode nil)2197(yas/direct-keymaps nil)2198(keys-1 (this-command-keys-vector))2199(keys-2 (and yas/trigger-key2200from-trigger-key-p2201(stringp yas/trigger-key)2202(read-kbd-macro yas/trigger-key)))2203(command-1 (and keys-1 (key-binding keys-1)))2204(command-2 (and keys-2 (key-binding keys-2)))2205;; An (ugly) safety: prevents infinite recursion of2206;; yas/expand* calls.2207(command (or (and (symbolp command-1)2208(not (string-match "yas/expand" (symbol-name command-1)))2209command-1)2210(and (symbolp command-2)2211command-2))))2212(when (and (commandp command)2213(not (string-match "yas/expand" (symbol-name command))))2214(setq this-command command)2215(call-interactively command))))2216((and (listp yas/fallback-behavior)2217(cdr yas/fallback-behavior)2218(eq 'apply (car yas/fallback-behavior)))2219(if (cddr yas/fallback-behavior)2220(apply (cadr yas/fallback-behavior)2221(cddr yas/fallback-behavior))2222(when (commandp (cadr yas/fallback-behavior))2223(setq this-command (cadr yas/fallback-behavior))2224(call-interactively (cadr yas/fallback-behavior)))))2225(t2226;; also return nil if all the other fallbacks have failed2227nil)))2228222922302231;;; Snippet development22322233(defun yas/all-templates (tables)2234"Return all snippet tables applicable for the current buffer.22352236Honours `yas/choose-tables-first', `yas/choose-keys-first' and2237`yas/buffer-local-condition'"2238(when yas/choose-tables-first2239(setq tables (list (yas/prompt-for-table tables))))2240(mapcar #'cdr2241(if yas/choose-keys-first2242(let ((key (yas/prompt-for-keys2243(mapcan #'yas/table-all-keys tables))))2244(when key2245(mapcan #'(lambda (table)2246(yas/fetch table key))2247tables)))2248(remove-duplicates (mapcan #'yas/table-templates tables)2249:test #'equal))))22502251(defun yas/insert-snippet (&optional no-condition)2252"Choose a snippet to expand, pop-up a list of choices according2253to `yas/prompt-function'.22542255With prefix argument NO-CONDITION, bypass filtering of snippets2256by condition."2257(interactive "P")2258(setq yas/condition-cache-timestamp (current-time))2259(let* ((yas/buffer-local-condition (or (and no-condition2260'always)2261yas/buffer-local-condition))2262(templates (yas/all-templates (yas/get-snippet-tables)))2263(yas/current-template (and templates2264(or (and (rest templates) ;; more than one template for same key2265(yas/prompt-for-template templates))2266(car templates))))2267(where (if (region-active-p)2268(cons (region-beginning) (region-end))2269(cons (point) (point)))))2270(if yas/current-template2271(yas/expand-snippet (yas/template-content yas/current-template)2272(car where)2273(cdr where)2274(yas/template-expand-env yas/current-template))2275(message "[yas] No snippets can be inserted here!"))))22762277(defun yas/visit-snippet-file ()2278"Choose a snippet to edit, selection like `yas/insert-snippet'.22792280Only success if selected snippet was loaded from a file. Put the2281visited file in `snippet-mode'."2282(interactive)2283(let* ((yas/buffer-local-condition 'always)2284(templates (yas/all-templates (yas/get-snippet-tables)))2285(yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))2286(template (and templates2287(or (yas/prompt-for-template templates2288"Choose a snippet template to edit: ")2289(car templates)))))22902291(if template2292(yas/visit-snippet-file-1 template)2293(message "No snippets tables active!"))))22942295(defun yas/visit-snippet-file-1 (template)2296(let ((file (yas/template-file template)))2297(cond ((and file (file-readable-p file))2298(find-file-other-window file)2299(snippet-mode)2300(set (make-local-variable 'yas/editing-template) template))2301(file2302(message "Original file %s no longer exists!" file))2303(t2304(switch-to-buffer (format "*%s*"(yas/template-name template)))2305(let ((type 'snippet))2306(when (listp (yas/template-content template))2307(insert (format "# type: command\n"))2308(setq type 'command))2309(insert (format "# key: %s\n" (yas/template-key template)))2310(insert (format "# name: %s\n" (yas/template-name template)))2311(when (yas/template-keybinding template)2312(insert (format "# binding: %s\n" (yas/template-keybinding template))))2313(when (yas/template-expand-env template)2314(insert (format "# expand-env: %s\n" (yas/template-expand-env template))))2315(when (yas/template-condition template)2316(insert (format "# condition: %s\n" (yas/template-condition template))))2317(insert "# --\n")2318(insert (if (eq type 'command)2319(pp-to-string (yas/template-content template))2320(yas/template-content template))))2321(snippet-mode)2322(set (make-local-variable 'yas/editing-template) template)))))23232324(defun yas/guess-snippet-directories-1 (table)2325"Guesses possible snippet subdirectories for TABLE."2326(cons (yas/table-name table)2327(mapcan #'(lambda (parent)2328(yas/guess-snippet-directories-12329parent))2330(yas/table-parents table))))23312332(defun yas/guess-snippet-directories (&optional table)2333"Try to guess suitable directories based on the current active2334tables (or optional TABLE).23352336Returns a list of elemts (TABLE . DIRS) where TABLE is a2337`yas/table' object and DIRS is a list of all possible directories2338where snippets of table might exist."2339(let ((main-dir (replace-regexp-in-string2340"/+$" ""2341(or (first (or (yas/snippet-dirs)2342(setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))2343(tables (or (and table2344(list table))2345(yas/get-snippet-tables))))2346;; HACK! the snippet table created here is actually registered!2347;;2348(unless (or table (gethash major-mode yas/tables))2349(push (yas/table-get-create major-mode)2350tables))23512352(mapcar #'(lambda (table)2353(cons table2354(mapcar #'(lambda (subdir)2355(concat main-dir "/" subdir))2356(yas/guess-snippet-directories-1 table))))2357tables)))23582359(defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)2360"Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."2361(or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))2362(let ((candidate (first (cdr table-and-dirs))))2363(unless (file-writable-p (file-name-directory candidate))2364(error "[yas] %s is not writable." candidate))2365(if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "2366candidate2367(if (gethash (intern (yas/table-name (car table-and-dirs)))2368yas/tables)2369""2370" brand new")2371(or main-table-string2372"")2373(yas/table-name (car table-and-dirs))))2374(progn2375(make-directory candidate 'also-make-parents)2376;; create the .yas-parents file here...2377candidate)))))23782379(defun yas/new-snippet (&optional choose-instead-of-guess)2380""2381(interactive "P")2382(let ((guessed-directories (yas/guess-snippet-directories)))23832384(switch-to-buffer "*new snippet*")2385(erase-buffer)2386(kill-all-local-variables)2387(snippet-mode)2388(set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)2389(intern (yas/table-name (car d))))2390guessed-directories))2391(unless (and choose-instead-of-guess2392(not (y-or-n-p "Insert a snippet with useful headers? ")))2393(yas/expand-snippet "\2394# -*- mode: snippet -*-2395# name: $12396# key: $2${3:2397# binding: ${4:direct-keybinding}}${5:2398# expand-env: ((${6:some-var} ${7:some-value}))}${8:2399# type: command}2400# --2401$0"))))24022403(defun yas/find-snippets (&optional same-window )2404"Find snippet file in guessed current mode's directory.24052406Calls `find-file' interactively in the guessed directory.24072408With prefix arg SAME-WINDOW opens the buffer in the same window.24092410Because snippets can be loaded from many different locations,2411this has to guess the correct directory using2412`yas/guess-snippet-directories', which returns a list of2413options.24142415If any one of these exists, it is taken and `find-file' is called2416there, otherwise, proposes to create the first option returned by2417`yas/guess-snippet-directories'."2418(interactive "P")2419(let* ((guessed-directories (yas/guess-snippet-directories))2420(chosen)2421(buffer))2422(setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))2423(unless chosen2424(if (y-or-n-p (format "Continue guessing for other active tables %s? "2425(mapcar #'(lambda (table-and-dirs)2426(yas/table-name (car table-and-dirs)))2427(rest guessed-directories))))2428(setq chosen (some #'yas/make-directory-maybe2429(rest guessed-directories)))))2430(unless chosen2431(when (y-or-n-p "Having trouble... go to snippet root dir? ")2432(setq chosen (first (yas/snippet-dirs)))))2433(if chosen2434(let ((default-directory chosen))2435(setq buffer (call-interactively (if same-window2436'find-file2437'find-file-other-window)))2438(when buffer2439(save-excursion2440(set-buffer buffer)2441(when (eq major-mode 'fundamental-mode)2442(snippet-mode)))))2443(message "Could not guess snippet dir!"))))24442445(defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)2446(let* ((file-dir (and file2447(directory-file-name (or (some #'(lambda (special)2448(locate-dominating-file file special))2449'(".yas-setup.el"2450".yas-make-groups"2451".yas-parents"))2452(directory-file-name (file-name-directory file))))))2453(parents-file-name (concat file-dir "/.yas-parents"))2454(major-mode-name (and file-dir2455(file-name-nondirectory file-dir)))2456(major-mode-sym (or (and major-mode-name2457(intern major-mode-name))2458(when prompt-if-failed2459(read-from-minibuffer2460"[yas] Cannot auto-detect major mode! Enter a major mode: "))))2461(parents (when (file-readable-p parents-file-name)2462(mapcar #'intern2463(split-string2464(with-temp-buffer2465(insert-file-contents parents-file-name)2466(buffer-substring-no-properties (point-min)2467(point-max))))))))2468(when major-mode-sym2469(cons major-mode-sym parents))))24702471(defvar yas/editing-template nil2472"Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")24732474(defvar yas/current-template nil2475"Holds the current template being expanded into a snippet.")24762477(defvar yas/guessed-modes nil2478"List of guessed modes supporting `yas/load-snippet-buffer'.")24792480(defun yas/load-snippet-buffer (&optional kill)2481"Parse and load current buffer's snippet definition.24822483With optional prefix argument KILL quit the window and buffer."2484(interactive "P")2485(let ((yas/ignore-filenames-as-triggers2486(or yas/ignore-filenames-as-triggers2487(and buffer-file-name2488(locate-dominating-file2489buffer-file-name2490".yas-ignore-filenames-as-triggers")))))2491(cond2492;; We have `yas/editing-template', this buffer's2493;; content comes from a template which is already loaded and2494;; neatly positioned,...2495;;2496(yas/editing-template2497(yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))2498(yas/template-table yas/editing-template)))2499;; Try to use `yas/guessed-modes'. If we don't have that use the2500;; value from `yas/compute-major-mode-and-parents'2501;;2502(t2503(unless yas/guessed-modes2504(set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))2505(let* ((prompt (if (and (featurep 'ido)2506ido-mode)2507'ido-completing-read 'completing-read))2508(table (yas/table-get-create2509(intern2510(funcall prompt (format "Choose or enter a table (yas guesses %s): "2511(if yas/guessed-modes2512(first yas/guessed-modes)2513"nothing"))2514(mapcar #'symbol-name yas/guessed-modes)2515nil2516nil2517nil2518nil2519(if (first yas/guessed-modes)2520(symbol-name (first yas/guessed-modes))))))))2521(set (make-local-variable 'yas/editing-template)2522(yas/define-snippets-1 (yas/parse-template buffer-file-name)2523table))))))2524;; Now, offer to save this shit2525;;2526;; 1) if `yas/snippet-dirs' is a list and its first element does not2527;; match this template's file (i.e. this is a library snippet, not2528;; a user snippet).2529;;2530;; 2) yas/editing-template comes from a file that we cannot write to...2531;;2532(when (or (not (yas/template-file yas/editing-template))2533(not (file-writable-p (yas/template-file yas/editing-template)))2534(and (listp yas/snippet-dirs)2535(second yas/snippet-dirs)2536(not (string-match (expand-file-name (first yas/snippet-dirs))2537(yas/template-file yas/editing-template)))))25382539(when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")2540(let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))2541(chosen (and option2542(yas/make-directory-maybe option))))2543(when chosen2544(let ((default-file-name (or (and (yas/template-file yas/editing-template)2545(file-name-nondirectory (yas/template-file yas/editing-template)))2546(yas/template-name yas/editing-template))))2547(write-file (concat chosen "/"2548(read-from-minibuffer (format "File name to create in %s? " chosen)2549default-file-name)))2550(setf (yas/template-file yas/editing-template) buffer-file-name))))))2551(when kill2552(quit-window kill))2553(message "[yas] Snippet \"%s\" loaded for %s."2554(yas/template-name yas/editing-template)2555(yas/table-name (yas/template-table yas/editing-template))))255625572558(defun yas/tryout-snippet (&optional debug)2559"Test current buffers's snippet template in other buffer."2560(interactive "P")2561(let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))2562(parsed (yas/parse-template))2563(test-mode (or (and (car major-mode-and-parent)2564(fboundp (car major-mode-and-parent))2565(car major-mode-and-parent))2566(first yas/guessed-modes)2567(intern (read-from-minibuffer "[yas] please input a mode: "))))2568(yas/current-template2569(and parsed2570(fboundp test-mode)2571(yas/populate-template (yas/make-blank-template)2572:table nil ;; no tables for ephemeral snippets2573:key (first parsed)2574:content (second parsed)2575:name (third parsed)2576:expand-env (sixth parsed)))))2577(cond (yas/current-template2578(let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))2579(kill-buffer (get-buffer-create buffer-name))2580(switch-to-buffer (get-buffer-create buffer-name))2581(setq buffer-undo-list nil)2582(condition-case nil (funcall test-mode) (error nil))2583(yas/expand-snippet (yas/template-content yas/current-template)2584(point-min)2585(point-max)2586(yas/template-expand-env yas/current-template))2587(when (and debug2588(require 'yasnippet-debug nil t))2589(add-hook 'post-command-hook 'yas/debug-snippet-vars 't 'local))))2590(t2591(message "[yas] Cannot test snippet for unknown major mode")))))25922593(defun yas/template-fine-group (template)2594(car (last (or (yas/template-group template)2595(yas/template-perm-group template)))))25962597(defun yas/describe-tables (&optional choose)2598"Display snippets for each table."2599(interactive "P")2600(let* ((by-name-hash (and choose2601(y-or-n-p "Show by namehash? ")))2602(buffer (get-buffer-create "*YASnippet tables*"))2603(active-tables (yas/get-snippet-tables))2604(remain-tables (let ((all))2605(maphash #'(lambda (k v)2606(unless (find v active-tables)2607(push v all)))2608yas/tables)2609all))2610(table-lists (list active-tables remain-tables))2611(original-buffer (current-buffer))2612(continue t)2613(yas/condition-cache-timestamp (current-time)))2614(with-current-buffer buffer2615(setq buffer-read-only nil)2616(erase-buffer)2617(cond ((not by-name-hash)2618(insert "YASnippet tables: \n")2619(while (and table-lists2620continue)2621(dolist (table (car table-lists))2622(yas/describe-pretty-table table original-buffer))2623(setq table-lists (cdr table-lists))2624(when table-lists2625(yas/create-snippet-xrefs)2626(display-buffer buffer)2627(setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))2628(yas/create-snippet-xrefs)2629(help-mode)2630(goto-char 1))2631(t2632(insert "\n\nYASnippet tables by NAMEHASH: \n")2633(dolist (table (append active-tables remain-tables))2634(insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))2635(let ((keys))2636(maphash #'(lambda (k v)2637(push k keys))2638(yas/table-hash table))2639(dolist (key keys)2640(insert (format " key %s maps snippets: %s\n" key2641(let ((names))2642(maphash #'(lambda (k v)2643(push k names))2644(gethash key (yas/table-hash table)))2645names))))))))2646(goto-char 1)2647(setq buffer-read-only t))2648(display-buffer buffer)))26492650(defun yas/describe-pretty-table (table &optional original-buffer)2651(insert (format "\nSnippet table `%s'"2652(yas/table-name table)))2653(if (yas/table-parents table)2654(insert (format " parents: %s\n"2655(mapcar #'yas/table-name2656(yas/table-parents table))))2657(insert "\n"))2658(insert (make-string 100 ?-) "\n")2659(insert "group state name key binding\n")2660(let ((groups-alist (list))2661group)2662(maphash #'(lambda (k v)2663(setq group (or (yas/template-fine-group v)2664"(top level)"))2665(when (yas/template-name v)26662667(aput 'groups-alist group (cons v (aget groups-alist group)))))2668(yas/table-uuidhash table))2669(dolist (group-and-templates groups-alist)2670(when (rest group-and-templates)2671(setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))2672(insert (make-string 100 ?-) "\n")2673(dolist (p (cdr group-and-templates))2674(let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))2675'yasnippet p)267650 0 ? "..."))2677(group (prog1 group2678(setq group (make-string (length group) ? ))))2679(condition-string (let ((condition (yas/template-condition p)))2680(if (and condition2681original-buffer)2682(with-current-buffer original-buffer2683(if (yas/eval-condition condition)2684"(y)"2685"(s)"))2686"(a)"))))2687(insert group " ")2688(insert condition-string " ")2689(insert name2690(if (string-match "\\.\\.\\.$" name)2691"'"2692" ")2693" ")2694(insert (truncate-string-to-width (or (yas/template-key p) "")269515 0 ? "...") " ")2696(insert (truncate-string-to-width (key-description (yas/template-keybinding p))269715 0 ? "...") " ")2698(insert "\n")))))))269927002701270227032704;;; User convenience functions, for using in snippet definitions27052706(defvar yas/modified-p nil2707"Non-nil if field has been modified by user or transformation.")27082709(defvar yas/moving-away-p nil2710"Non-nil if user is about to exit field.")27112712(defvar yas/text nil2713"Contains current field text.")27142715(defun yas/substr (str pattern &optional subexp)2716"Search PATTERN in STR and return SUBEXPth match.27172718If found, the content of subexp group SUBEXP (default 0) is2719returned, or else the original STR will be returned."2720(let ((grp (or subexp 0)))2721(save-match-data2722(if (string-match pattern str)2723(match-string-no-properties grp str)2724str))))27252726(defun yas/choose-value (possibilities)2727"Prompt for a string in the list POSSIBILITIES and return it."2728(unless (or yas/moving-away-p2729yas/modified-p)2730(some #'(lambda (fn)2731(funcall fn "Choose: " possibilities))2732yas/prompt-functions)))27332734(defun yas/key-to-value (alist)2735"Prompt for a string in the list POSSIBILITIES and return it."2736(unless (or yas/moving-away-p2737yas/modified-p)2738(let ((key (read-key-sequence "")))2739(when (stringp key)2740(or (cdr (find key alist :key #'car :test #'string=))2741key)))))27422743(defun yas/throw (text)2744"Throw a yas/exception with TEXT as the reason."2745(throw 'yas/exception (cons 'yas/exception text)))27462747(defun yas/verify-value (possibilities)2748"Verify that the current field value is in POSSIBILITIES27492750Otherwise throw exception."2751(when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))2752(yas/throw (format "[yas] field only allows %s" possibilities))))27532754(defun yas/field-value (number)2755"Get the string for field with NUMBER.27562757Use this in primary and mirror transformations to tget."2758(let* ((snippet (car (yas/snippets-at-point)))2759(field (and snippet2760(yas/snippet-find-field snippet number))))2761(when field2762(yas/field-text-for-display field))))27632764(defun yas/text ()2765"Return `yas/text' if that exists and is non-empty, else nil."2766(if (and yas/text2767(not (string= "" yas/text)))2768yas/text))27692770;; (defun yas/selected-text ()2771;; "Return `yas/selected-text' if that exists and is non-empty, else nil."2772;; (if (and yas/selected-text2773;; (not (string= "" yas/selected-text)))2774;; yas/selected-text))27752776(defun yas/get-field-once (number &optional transform-fn)2777(unless yas/modified-p2778(if transform-fn2779(funcall transform-fn (yas/field-value number))2780(yas/field-value number))))27812782(defun yas/default-from-field (number)2783(unless yas/modified-p2784(yas/field-value number)))27852786(defun yas/inside-string ()2787(equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))27882789(defun yas/unimplemented ()2790(if yas/current-template2791(if (y-or-n-p "This snippet is unimplemented. Visit the snippet definition? ")2792(yas/visit-snippet-file-1 yas/current-template))2793(message "No implementation.")))279427952796;;; Snippet expansion and field management27972798(defvar yas/active-field-overlay nil2799"Overlays the currently active field.")28002801(defvar yas/field-protection-overlays nil2802"Two overlays protect the current active field ")28032804(defconst yas/prefix nil2805"A prefix argument for expansion direct from keybindings")28062807(defvar yas/deleted-text nil2808"The text deleted in the last snippet expansion.")28092810(defvar yas/selected-text nil2811"The selected region deleted on the last snippet expansion.")28122813(defvar yas/start-column nil2814"The column where the snippet expansion started.")28152816(make-variable-buffer-local 'yas/active-field-overlay)2817(make-variable-buffer-local 'yas/field-protection-overlays)2818(make-variable-buffer-local 'yas/deleted-text)28192820(defstruct (yas/snippet (:constructor yas/make-snippet ()))2821"A snippet.28222823..."2824(fields '())2825(exit nil)2826(id (yas/snippet-next-id) :read-only t)2827(control-overlay nil)2828active-field2829;; stacked expansion: the `previous-active-field' slot saves the2830;; active field where the child expansion took place2831previous-active-field2832force-exit)28332834(defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))2835"A field."2836number2837start end2838parent-field2839(mirrors '())2840(transform nil)2841(modified-p nil)2842next)28432844(defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))2845"A mirror."2846start end2847(transform nil)2848parent-field2849next)28502851(defstruct (yas/exit (:constructor yas/make-exit (marker)))2852marker2853next)28542855(defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)2856"Calculate transformed string for FIELD-OR-MIRROR from FIELD.28572858If there is no transform for ht field, return nil.28592860If there is a transform but it returns nil, return the empty2861string iff EMPTY-ON-NIL-P is true."2862(let* ((yas/text (yas/field-text-for-display field))2863(text yas/text)2864(yas/modified-p (yas/field-modified-p field))2865(yas/moving-away-p nil)2866(transform (if (yas/mirror-p field-or-mirror)2867(yas/mirror-transform field-or-mirror)2868(yas/field-transform field-or-mirror)))2869(start-point (if (yas/mirror-p field-or-mirror)2870(yas/mirror-start field-or-mirror)2871(yas/field-start field-or-mirror)))2872(transformed (and transform2873(save-excursion2874(goto-char start-point)2875(let ((ret (yas/eval-lisp transform)))2876(or ret (and empty-on-nil-p "")))))))2877transformed))28782879(defsubst yas/replace-all (from to &optional text)2880"Replace all occurance from FROM to TO.28812882With optional string TEXT do it in that string."2883(if text2884(replace-regexp-in-string (regexp-quote from) to text t t)2885(goto-char (point-min))2886(while (search-forward from nil t)2887(replace-match to t t text))))28882889(defun yas/snippet-find-field (snippet number)2890(find-if #'(lambda (field)2891(eq number (yas/field-number field)))2892(yas/snippet-fields snippet)))28932894(defun yas/snippet-sort-fields (snippet)2895"Sort the fields of SNIPPET in navigation order."2896(setf (yas/snippet-fields snippet)2897(sort (yas/snippet-fields snippet)2898#'yas/snippet-field-compare)))28992900(defun yas/snippet-field-compare (field1 field2)2901"Compare two fields. The field with a number is sorted first.2902If they both have a number, compare through the number. If neither2903have, compare through the field's start point"2904(let ((n1 (yas/field-number field1))2905(n2 (yas/field-number field2)))2906(if n12907(if n22908(or (zerop n2) (and (not (zerop n1))2909(< n1 n2)))2910(not (zerop n1)))2911(if n22912(zerop n2)2913(< (yas/field-start field1)2914(yas/field-start field2))))))29152916(defun yas/field-probably-deleted-p (snippet field)2917"Guess if SNIPPET's FIELD should be skipped."2918(and (zerop (- (yas/field-start field) (yas/field-end field)))2919(or (yas/field-parent-field field)2920(and (eq field (car (last (yas/snippet-fields snippet))))2921(= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))2922;; the field numbered 0, just before the exit marker, should2923;; never be skipped2924(not (zerop (yas/field-number field)))))29252926(defun yas/snippets-at-point (&optional all-snippets)2927"Return a sorted list of snippets at point, most recently2928inserted first."2929(sort2930(remove nil (remove-duplicates (mapcar #'(lambda (ov)2931(overlay-get ov 'yas/snippet))2932(if all-snippets2933(overlays-in (point-min) (point-max))2934(overlays-at (point))))))2935#'(lambda (s1 s2)2936(<= (yas/snippet-id s2) (yas/snippet-id s1)))))29372938(defun yas/next-field-or-maybe-expand ()2939"Try to expand a snippet at a key before point, otherwise2940delegate to `yas/next-field'."2941(interactive)2942(if yas/triggers-in-field2943(let ((yas/fallback-behavior 'return-nil)2944(active-field (overlay-get yas/active-field-overlay 'yas/field)))2945(when active-field2946(unless (yas/expand-from-trigger-key active-field)2947(yas/next-field))))2948(yas/next-field)))29492950(defun yas/next-field (&optional arg)2951"Navigate to next field. If there's none, exit the snippet."2952(interactive)2953(let* ((arg (or arg29541))2955(snippet (first (yas/snippets-at-point)))2956(active-field (overlay-get yas/active-field-overlay 'yas/field))2957(live-fields (remove-if #'(lambda (field)2958(and (not (eq field active-field))2959(yas/field-probably-deleted-p snippet field)))2960(yas/snippet-fields snippet)))2961(active-field-pos (position active-field live-fields))2962(target-pos (and active-field-pos (+ arg active-field-pos)))2963(target-field (nth target-pos live-fields)))2964;; First check if we're moving out of a field with a transform2965;;2966(when (and active-field2967(yas/field-transform active-field))2968(let* ((yas/moving-away-p t)2969(yas/text (yas/field-text-for-display active-field))2970(text yas/text)2971(yas/modified-p (yas/field-modified-p active-field)))2972;; primary field transform: exit call to field-transform2973(yas/eval-lisp (yas/field-transform active-field))))2974;; Now actually move...2975(cond ((>= target-pos (length live-fields))2976(yas/exit-snippet snippet))2977(target-field2978(yas/move-to-field snippet target-field))2979(t2980nil))))29812982(defun yas/place-overlays (snippet field)2983"Correctly place overlays for SNIPPET's FIELD"2984(yas/make-move-field-protection-overlays snippet field)2985(yas/make-move-active-field-overlay snippet field))29862987(defun yas/move-to-field (snippet field)2988"Update SNIPPET to move to field FIELD.29892990Also create some protection overlays"2991(goto-char (yas/field-start field))2992(yas/place-overlays snippet field)2993(overlay-put yas/active-field-overlay 'yas/field field)2994(let ((number (yas/field-number field)))2995;; check for the special ${0: ...} field2996(if (and number (zerop number))2997(progn2998(set-mark (yas/field-end field))2999(setf (yas/snippet-force-exit snippet)3000(or (yas/field-transform field)3001t)))3002;; make this field active3003(setf (yas/snippet-active-field snippet) field)3004;; primary field transform: first call to snippet transform3005(unless (yas/field-modified-p field)3006(if (yas/field-update-display field snippet)3007(let ((inhibit-modification-hooks t))3008(yas/update-mirrors snippet))3009(setf (yas/field-modified-p field) nil))))))30103011(defun yas/prev-field ()3012"Navigate to prev field. If there's none, exit the snippet."3013(interactive)3014(yas/next-field -1))30153016(defun yas/abort-snippet (&optional snippet)3017(interactive)3018(let ((snippet (or snippet3019(car (yas/snippets-at-point)))))3020(when snippet3021(setf (yas/snippet-force-exit snippet) t))))30223023(defun yas/exit-snippet (snippet)3024"Goto exit-marker of SNIPPET."3025(interactive)3026(setf (yas/snippet-force-exit snippet) t)3027(goto-char (if (yas/snippet-exit snippet)3028(yas/exit-marker (yas/snippet-exit snippet))3029(overlay-end (yas/snippet-control-overlay snippet)))))30303031(defun yas/exit-all-snippets ()3032"Exit all snippets."3033(interactive)3034(mapc #'(lambda (snippet)3035(yas/exit-snippet snippet)3036(yas/check-commit-snippet))3037(yas/snippets-at-point)))303830393040;;; Some low level snippet-routines30413042(defun yas/commit-snippet (snippet)3043"Commit SNIPPET, but leave point as it is. This renders the3044snippet as ordinary text.30453046Return a buffer position where the point should be placed if3047exiting the snippet.30483049NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."30503051(let ((control-overlay (yas/snippet-control-overlay snippet))3052yas/snippet-beg3053yas/snippet-end)3054;;3055;; Save the end of the moribund snippet in case we need to revive it3056;; its original expansion.3057;;3058(when (and control-overlay3059(overlay-buffer control-overlay))3060(setq yas/snippet-beg (overlay-start control-overlay))3061(setq yas/snippet-end (overlay-end control-overlay))3062(delete-overlay control-overlay))30633064(let ((inhibit-modification-hooks t))3065(when yas/active-field-overlay3066(delete-overlay yas/active-field-overlay))3067(when yas/field-protection-overlays3068(mapc #'delete-overlay yas/field-protection-overlays)))30693070;; stacked expansion: if the original expansion took place from a3071;; field, make sure we advance it here at least to3072;; `yas/snippet-end'...3073;;3074(let ((previous-field (yas/snippet-previous-active-field snippet)))3075(when (and yas/snippet-end previous-field)3076(yas/advance-end-maybe previous-field yas/snippet-end)))30773078;; Convert all markers to points,3079;;3080(yas/markers-to-points snippet)30813082;; Take care of snippet revival3083;;3084(if yas/snippet-revival3085(push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)3086buffer-undo-list)3087;; Dismember the snippet... this is useful if we get called3088;; again from `yas/take-care-of-redo'....3089(setf (yas/snippet-fields snippet) nil)))30903091(message "[yas] snippet %s exited." (yas/snippet-id snippet)))30923093(defun yas/check-commit-snippet ()3094"Checks if point exited the currently active field of the3095snippet, if so cleans up the whole snippet up."3096(let* ((snippets (yas/snippets-at-point 'all-snippets))3097(snippets-left snippets)3098(snippet-exit-transform))3099(dolist (snippet snippets)3100(let ((active-field (yas/snippet-active-field snippet)))3101(setq snippet-exit-transform (yas/snippet-force-exit snippet))3102(cond ((or snippet-exit-transform3103(not (and active-field (yas/field-contains-point-p active-field))))3104(setq snippets-left (delete snippet snippets-left))3105(setf (yas/snippet-force-exit snippet) nil)3106(yas/commit-snippet snippet))3107((and active-field3108(or (not yas/active-field-overlay)3109(not (overlay-buffer yas/active-field-overlay))))3110;;3111;; stacked expansion: this case is mainly for recent3112;; snippet exits that place us back int the field of3113;; another snippet3114;;3115(save-excursion3116(yas/move-to-field snippet active-field)3117(yas/update-mirrors snippet)))3118(t3119nil))))3120(unless snippets-left3121(remove-hook 'post-command-hook 'yas/post-command-handler 'local)3122(remove-hook 'pre-command-hook 'yas/pre-command-handler 'local)3123(if snippet-exit-transform3124(yas/eval-lisp-no-saves snippet-exit-transform)3125(run-hooks 'yas/after-exit-snippet-hook)))))31263127;; Apropos markers-to-points:3128;;3129;; This was found useful for performance reasons, so that an3130;; excessive number of live markers aren't kept around in the3131;; `buffer-undo-list'. However, in `markers-to-points', the3132;; set-to-nil markers can't simply be discarded and replaced with3133;; fresh ones in `points-to-markers'. The original marker that was3134;; just set to nil has to be reused.3135;;3136;; This shouldn't bring horrible problems with undo/redo, but it3137;; you never know3138;;3139(defun yas/markers-to-points (snippet)3140"Convert all markers in SNIPPET to a cons (POINT . MARKER)3141where POINT is the original position of the marker and MARKER is3142the original marker object with the position set to nil."3143(dolist (field (yas/snippet-fields snippet))3144(let ((start (marker-position (yas/field-start field)))3145(end (marker-position (yas/field-end field))))3146(set-marker (yas/field-start field) nil)3147(set-marker (yas/field-end field) nil)3148(setf (yas/field-start field) (cons start (yas/field-start field)))3149(setf (yas/field-end field) (cons end (yas/field-end field))))3150(dolist (mirror (yas/field-mirrors field))3151(let ((start (marker-position (yas/mirror-start mirror)))3152(end (marker-position (yas/mirror-end mirror))))3153(set-marker (yas/mirror-start mirror) nil)3154(set-marker (yas/mirror-end mirror) nil)3155(setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))3156(setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))3157(let ((snippet-exit (yas/snippet-exit snippet)))3158(when snippet-exit3159(let ((exit (marker-position (yas/exit-marker snippet-exit))))3160(set-marker (yas/exit-marker snippet-exit) nil)3161(setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))31623163(defun yas/points-to-markers (snippet)3164"Convert all cons (POINT . MARKER) in SNIPPET to markers. This3165is done by setting MARKER to POINT with `set-marker'."3166(dolist (field (yas/snippet-fields snippet))3167(setf (yas/field-start field) (set-marker (cdr (yas/field-start field))3168(car (yas/field-start field))))3169(setf (yas/field-end field) (set-marker (cdr (yas/field-end field))3170(car (yas/field-end field))))3171(dolist (mirror (yas/field-mirrors field))3172(setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))3173(car (yas/mirror-start mirror))))3174(setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))3175(car (yas/mirror-end mirror))))))3176(let ((snippet-exit (yas/snippet-exit snippet)))3177(when snippet-exit3178(setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))3179(car (yas/exit-marker snippet-exit)))))))31803181(defun yas/field-contains-point-p (field &optional point)3182(let ((point (or point3183(point))))3184(and (>= point (yas/field-start field))3185(<= point (yas/field-end field)))))31863187(defun yas/field-text-for-display (field)3188"Return the propertized display text for field FIELD. "3189(buffer-substring (yas/field-start field) (yas/field-end field)))31903191(defun yas/undo-in-progress ()3192"True if some kind of undo is in progress"3193(or undo-in-progress3194(eq this-command 'undo)3195(eq this-command 'redo)))31963197(defun yas/make-control-overlay (snippet start end)3198"Creates the control overlay that surrounds the snippet and3199holds the keymap."3200(let ((overlay (make-overlay start3201end3202nil3203nil3204t)))3205(overlay-put overlay 'keymap yas/keymap)3206(overlay-put overlay 'yas/snippet snippet)3207overlay))32083209(defun yas/skip-and-clear-or-delete-char (&optional field)3210"Clears unmodified field if at field start, skips to next tab.32113212Otherwise deletes a character normally by calling `delete-char'."3213(interactive)3214(let ((field (or field3215(and yas/active-field-overlay3216(overlay-buffer yas/active-field-overlay)3217(overlay-get yas/active-field-overlay 'yas/field)))))3218(cond ((and field3219(not (yas/field-modified-p field))3220(eq (point) (marker-position (yas/field-start field))))3221(yas/skip-and-clear field)3222(yas/next-field 1))3223(t3224(call-interactively 'delete-char)))))32253226(defun yas/skip-and-clear (field)3227"Deletes the region of FIELD and sets it modified state to t"3228;; Just before skipping-and-clearing the field, mark its children3229;; fields as modified, too. If the childen have mirrors-in-fields3230;; this prevents them from updating erroneously (we're skipping and3231;; deleting!).3232;;3233(yas/mark-this-and-children-modified field)3234(delete-region (yas/field-start field) (yas/field-end field)))32353236(defun yas/mark-this-and-children-modified (field)3237(setf (yas/field-modified-p field) t)3238(let ((fom (yas/field-next field)))3239(while (and fom3240(yas/fom-parent-field fom))3241(when (and (eq (yas/fom-parent-field fom) field)3242(yas/field-p fom))3243(yas/mark-this-and-children-modified fom))3244(setq fom (yas/fom-next fom)))))32453246(defun yas/make-move-active-field-overlay (snippet field)3247"Place the active field overlay in SNIPPET's FIELD.32483249Move the overlay, or create it if it does not exit."3250(if (and yas/active-field-overlay3251(overlay-buffer yas/active-field-overlay))3252(move-overlay yas/active-field-overlay3253(yas/field-start field)3254(yas/field-end field))3255(setq yas/active-field-overlay3256(make-overlay (yas/field-start field)3257(yas/field-end field)3258nil nil t))3259(overlay-put yas/active-field-overlay 'priority 100)3260(overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)3261(overlay-put yas/active-field-overlay 'yas/snippet snippet)3262(overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))3263(overlay-put yas/active-field-overlay 'insert-in-front-hooks3264'(yas/on-field-overlay-modification))3265(overlay-put yas/active-field-overlay 'insert-behind-hooks3266'(yas/on-field-overlay-modification))))32673268(defun yas/on-field-overlay-modification (overlay after? beg end &optional length)3269"Clears the field and updates mirrors, conditionally.32703271Only clears the field if it hasn't been modified and it point it3272at field start. This hook doesn't do anything if an undo is in3273progress."3274(unless (yas/undo-in-progress)3275(let* ((field (overlay-get yas/active-field-overlay 'yas/field))3276(number (and field (yas/field-number field)))3277(snippet (overlay-get yas/active-field-overlay 'yas/snippet)))3278(cond (after?3279(yas/advance-end-maybe field (overlay-end overlay))3280(let ((saved-point (point)))3281(yas/field-update-display field (car (yas/snippets-at-point)))3282(goto-char saved-point))3283(yas/update-mirrors (car (yas/snippets-at-point))))3284(field3285(when (and (not after?)3286(not (yas/field-modified-p field))3287(eq (point) (if (markerp (yas/field-start field))3288(marker-position (yas/field-start field))3289(yas/field-start field))))3290(yas/skip-and-clear field))3291(setf (yas/field-modified-p field) t))))))32923293;;; Apropos protection overlays:3294;;3295;; These exist for nasty users who will try to delete parts of the3296;; snippet outside the active field. Actual protection happens in3297;; `yas/on-protection-overlay-modification'.3298;;3299;; Currently this signals an error which inhibits the command. For3300;; commands that move point (like `kill-line'), point is restored in3301;; the `yas/post-command-handler' using a global3302;; `yas/protection-violation' variable.3303;;3304;; Alternatively, I've experimented with an implementation that3305;; commits the snippet before actually calling `this-command'3306;; interactively, and then signals an eror, which is ignored. but3307;; blocks all other million modification hooks. This presented some3308;; problems with stacked expansion.3309;;33103311(defun yas/make-move-field-protection-overlays (snippet field)3312"Place protection overlays surrounding SNIPPET's FIELD.33133314Move the overlays, or create them if they do not exit."3315(let ((start (yas/field-start field))3316(end (yas/field-end field)))3317;; First check if the (1+ end) is contained in the buffer,3318;; otherwise we'll have to do a bit of cheating and silently3319;; insert a newline. the `(1+ (buffer-size))' should prevent this3320;; when using stacked expansion3321;;3322(when (< (buffer-size) end)3323(save-excursion3324(let ((inhibit-modification-hooks t))3325(goto-char (point-max))3326(newline))))3327;; go on to normal overlay creation/moving3328;;3329(cond ((and yas/field-protection-overlays3330(every #'overlay-buffer yas/field-protection-overlays))3331(move-overlay (first yas/field-protection-overlays) (1- start) start)3332(move-overlay (second yas/field-protection-overlays) end (1+ end)))3333(t3334(setq yas/field-protection-overlays3335(list (make-overlay (1- start) start nil t nil)3336(make-overlay end (1+ end) nil t nil)))3337(dolist (ov yas/field-protection-overlays)3338(overlay-put ov 'face 'yas/field-debug-face)3339(overlay-put ov 'yas/snippet snippet)3340;; (overlay-put ov 'evaporate t)3341(overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))33423343(defvar yas/protection-violation nil3344"When non-nil, signals attempts to erronesly exit or modify the snippet.33453346Functions in the `post-command-hook', for example3347`yas/post-command-handler' can check it and reset its value to3348nil. The variables value is the point where the violation3349originated")33503351(defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)3352"Signals a snippet violation, then issues error.33533354The error should be ignored in `debug-ignored-errors'"3355(cond ((not (or after?3356(yas/undo-in-progress)))3357(setq yas/protection-violation (point))3358(error "Exit the snippet first!"))))33593360(add-to-list 'debug-ignored-errors "^Exit the snippet first!$")336133623363;;; Apropos stacked expansion:3364;;3365;; the parent snippet does not run its fields modification hooks3366;; (`yas/on-field-overlay-modification' and3367;; `yas/on-protection-overlay-modification') while the child snippet3368;; is active. This means, among other things, that the mirrors of the3369;; parent snippet are not updated, this only happening when one exits3370;; the child snippet.3371;;3372;; Unfortunately, this also puts some ugly (and not fully-tested)3373;; bits of code in `yas/expand-snippet' and3374;; `yas/commit-snippet'. I've tried to mark them with "stacked3375;; expansion:".3376;;3377;; This was thought to be safer in in an undo/redo perpective, but3378;; maybe the correct implementation is to make the globals3379;; `yas/active-field-overlay' and `yas/field-protection-overlays' be3380;; snippet-local and be active even while the child snippet is3381;; running. This would mean a lot of overlay modification hooks3382;; running, but if managed correctly (including overlay priorities)3383;; they should account for all situations...3384;;33853386(defun yas/expand-snippet (content &optional start end expand-env)3387"Expand snippet CONTENT at current point.33883389Text between START and END will be deleted before inserting3390template. EXPAND-ENV is are let-style variable to value bindings3391considered when expanding the snippet."3392(run-hooks 'yas/before-expand-snippet-hook)33933394;; If a region is active, set `yas/selected-text'3395(setq yas/selected-text3396(when (region-active-p)3397(prog1 (buffer-substring-no-properties (region-beginning)3398(region-end))3399(unless start (setq start (region-beginning))3400(unless end (setq end (region-end)))))))34013402(when start3403(goto-char start))34043405;;3406(let ((to-delete (and start end (buffer-substring-no-properties start end)))3407(start (or start (point)))3408(end (or end (point)))3409snippet)3410(setq yas/indent-original-column (current-column))3411;; Delete the region to delete, this *does* get undo-recorded.3412;;3413(when (and to-delete3414(> end start))3415(delete-region start end)3416(setq yas/deleted-text to-delete))34173418(cond ((listp content)3419;; x) This is a snippet-command3420;;3421(yas/eval-lisp-no-saves content))3422(t3423;; x) This is a snippet-snippet :-)3424;;3425;; Narrow the region down to the content, shoosh the3426;; `buffer-undo-list', and create the snippet, the new3427;; snippet updates its mirrors once, so we are left with3428;; some plain text. The undo action for deleting this3429;; plain text will get recorded at the end.3430;;3431;; stacked expansion: also shoosh the overlay modification hooks3432(save-restriction3433(narrow-to-region start start)3434(let ((inhibit-modification-hooks t)3435(buffer-undo-list t))3436;; snippet creation might evaluate users elisp, which3437;; might generate errors, so we have to be ready to catch3438;; them mostly to make the undo information3439;;3440(setq yas/start-column (save-restriction (widen) (current-column)))34413442(setq snippet3443(if expand-env3444(eval `(let ,expand-env3445(insert content)3446(yas/snippet-create (point-min) (point-max))))3447(insert content)3448(yas/snippet-create (point-min) (point-max))))))34493450;; stacked-expansion: This checks for stacked expansion, save the3451;; `yas/previous-active-field' and advance its boudary.3452;;3453(let ((existing-field (and yas/active-field-overlay3454(overlay-buffer yas/active-field-overlay)3455(overlay-get yas/active-field-overlay 'yas/field))))3456(when existing-field3457(setf (yas/snippet-previous-active-field snippet) existing-field)3458(yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))34593460;; Exit the snippet immediately if no fields3461;;3462(unless (yas/snippet-fields snippet)3463(yas/exit-snippet snippet))34643465;; Push two undo actions: the deletion of the inserted contents of3466;; the new snippet (without the "key") followed by an apply of3467;; `yas/take-care-of-redo' on the newly inserted snippet boundaries3468;;3469;; A small exception, if `yas/also-auto-indent-first-line'3470;; is t and `yas/indent' decides to indent the line to a3471;; point before the actual expansion point, undo would be3472;; messed up. We call the early point "newstart"". case,3473;; and attempt to fix undo.3474;;3475(let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))3476(end (overlay-end (yas/snippet-control-overlay snippet))))3477(when (< newstart start)3478(push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))3479(push (cons newstart end) buffer-undo-list)3480(push `(apply yas/take-care-of-redo ,start ,end ,snippet)3481buffer-undo-list))3482;; Now, schedule a move to the first field3483;;3484(let ((first-field (car (yas/snippet-fields snippet))))3485(when first-field3486(sit-for 0) ;; fix issue 1253487(yas/move-to-field snippet first-field)))3488(message "[yas] snippet expanded.")3489t))))34903491(defun yas/take-care-of-redo (beg end snippet)3492"Commits SNIPPET, which in turn pushes an undo action for3493reviving it.34943495Meant to exit in the `buffer-undo-list'."3496;; slightly optimize: this action is only needed for snippets with3497;; at least one field3498(when (yas/snippet-fields snippet)3499(yas/commit-snippet snippet)))35003501(defun yas/snippet-revive (beg end snippet)3502"Revives the SNIPPET and creates a control overlay from BEG to3503END.35043505BEG and END are, we hope, the original snippets boudaries. All3506the markers/points exiting existing inside SNIPPET should point3507to their correct locations *at the time the snippet is revived*.35083509After revival, push the `yas/take-care-of-redo' in the3510`buffer-undo-list'"3511;; Reconvert all the points to markers3512;;3513(yas/points-to-markers snippet)3514;; When at least one editable field existed in the zombie snippet,3515;; try to revive the whole thing...3516;;3517(let ((target-field (or (yas/snippet-active-field snippet)3518(car (yas/snippet-fields snippet)))))3519(when target-field3520(setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))3521(overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)35223523(yas/move-to-field snippet target-field)35243525(add-hook 'post-command-hook 'yas/post-command-handler nil t)3526(add-hook 'pre-command-hook 'yas/pre-command-handler t t)35273528(push `(apply yas/take-care-of-redo ,beg ,end ,snippet)3529buffer-undo-list))))35303531(defun yas/snippet-create (begin end)3532"Creates a snippet from an template inserted between BEGIN and END.35333534Returns the newly created snippet."3535(let ((snippet (yas/make-snippet)))3536(goto-char begin)3537(yas/snippet-parse-create snippet)35383539;; Sort and link each field3540(yas/snippet-sort-fields snippet)35413542;; Create keymap overlay for snippet3543(setf (yas/snippet-control-overlay snippet)3544(yas/make-control-overlay snippet (point-min) (point-max)))35453546;; Move to end3547(goto-char (point-max))35483549;; Setup hooks3550(add-hook 'post-command-hook 'yas/post-command-handler nil t)3551(add-hook 'pre-command-hook 'yas/pre-command-handler t t)35523553snippet))355435553556;;; Apropos adjacencies and "fom's":3557;;3558;; Once the $-constructs bits like "$n" and "${:n" are deleted in the3559;; recently expanded snippet, we might actually have many fields,3560;; mirrors (and the snippet exit) in the very same position in the3561;; buffer. Therefore we need to single-link the3562;; fields-or-mirrors-or-exit, which I have called "fom", according to3563;; their original positions in the buffer.3564;;3565;; Then we have operation `yas/advance-end-maybe' and3566;; `yas/advance-start-maybe', which conditionally push the starts and3567;; ends of these foms down the chain.3568;;3569;; This allows for like the printf with the magic ",":3570;;3571;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \3572;; $2${1:$(if (string-match "%" text) "\);" "")}$03573;;3574(defun yas/fom-start (fom)3575(cond ((yas/field-p fom)3576(yas/field-start fom))3577((yas/mirror-p fom)3578(yas/mirror-start fom))3579(t3580(yas/exit-marker fom))))35813582(defun yas/fom-end (fom)3583(cond ((yas/field-p fom)3584(yas/field-end fom))3585((yas/mirror-p fom)3586(yas/mirror-end fom))3587(t3588(yas/exit-marker fom))))35893590(defun yas/fom-next (fom)3591(cond ((yas/field-p fom)3592(yas/field-next fom))3593((yas/mirror-p fom)3594(yas/mirror-next fom))3595(t3596(yas/exit-next fom))))35973598(defun yas/fom-parent-field (fom)3599(cond ((yas/field-p fom)3600(yas/field-parent-field fom))3601((yas/mirror-p fom)3602(yas/mirror-parent-field fom))3603(t3604nil)))36053606(defun yas/calculate-adjacencies (snippet)3607"Calculate adjacencies for fields or mirrors of SNIPPET.36083609This is according to their relative positions in the buffer, and3610has to be called before the $-constructs are deleted."3611(flet ((yas/fom-set-next-fom (fom nextfom)3612(cond ((yas/field-p fom)3613(setf (yas/field-next fom) nextfom))3614((yas/mirror-p fom)3615(setf (yas/mirror-next fom) nextfom))3616(t3617(setf (yas/exit-next fom) nextfom))))3618(yas/compare-fom-begs (fom1 fom2)3619(if (= (yas/fom-start fom2) (yas/fom-start fom1))3620(yas/mirror-p fom2)3621(>= (yas/fom-start fom2) (yas/fom-start fom1))))3622(yas/link-foms (fom1 fom2)3623(yas/fom-set-next-fom fom1 fom2)))3624;; make some yas/field, yas/mirror and yas/exit soup3625(let ((soup))3626(when (yas/snippet-exit snippet)3627(push (yas/snippet-exit snippet) soup))3628(dolist (field (yas/snippet-fields snippet))3629(push field soup)3630(dolist (mirror (yas/field-mirrors field))3631(push mirror soup)))3632(setq soup3633(sort soup3634#'yas/compare-fom-begs))3635(when soup3636(reduce #'yas/link-foms soup)))))36373638(defun yas/calculate-mirrors-in-fields (snippet mirror)3639"Attempt to assign a parent field of SNIPPET to the mirror MIRROR.36403641Use the tighest containing field if more than one field contains3642the mirror. Intended to be called *before* the dollar-regions are3643deleted."3644(let ((min (point-min))3645(max (point-max)))3646(dolist (field (yas/snippet-fields snippet))3647(when (and (<= (yas/field-start field) (yas/mirror-start mirror))3648(<= (yas/mirror-end mirror) (yas/field-end field))3649(< min (yas/field-start field))3650(< (yas/field-end field) max))3651(setq min (yas/field-start field)3652max (yas/field-end field))3653(setf (yas/mirror-parent-field mirror) field)))))36543655(defun yas/advance-end-maybe (fom newend)3656"Maybe advance FOM's end to NEWEND if it needs it.36573658If it does, also:36593660* call `yas/advance-start-maybe' on FOM's next fom.36613662* in case FOM is field call `yas/advance-end-maybe' on its parent3663field36643665Also, if FOM is an exit-marker, always call3666`yas/advance-start-maybe' on its next fom. This is beacuse3667exit-marker have identical start and end markers.36683669"3670(cond ((and fom (< (yas/fom-end fom) newend))3671(set-marker (yas/fom-end fom) newend)3672(yas/advance-start-maybe (yas/fom-next fom) newend)3673(let ((parent (yas/fom-parent-field fom)))3674(when parent3675(yas/advance-end-maybe parent newend))))3676((yas/exit-p fom)3677(yas/advance-start-maybe (yas/fom-next fom) newend))))36783679(defun yas/advance-start-maybe (fom newstart)3680"Maybe advance FOM's start to NEWSTART if it needs it.36813682If it does, also call `yas/advance-end-maybe' on FOM."3683(when (and fom (< (yas/fom-start fom) newstart))3684(set-marker (yas/fom-start fom) newstart)3685(yas/advance-end-maybe fom newstart)))36863687(defun yas/advance-end-of-parents-maybe (field newend)3688"Like `yas/advance-end-maybe' but for parents."3689(when (and field3690(< (yas/field-end field) newend))3691(set-marker (yas/field-end field) newend)3692(yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))36933694(defvar yas/dollar-regions nil3695"When expanding the snippet the \"parse-create\" functions add3696cons cells to this var")36973698(defun yas/snippet-parse-create (snippet)3699"Parse a recently inserted snippet template, creating all3700necessary fields, mirrors and exit points.37013702Meant to be called in a narrowed buffer, does various passes"3703(let ((parse-start (point)))3704;; Reset the yas/dollar-regions3705;;3706(setq yas/dollar-regions nil)3707;; protect escaped quote, backquotes and backslashes3708;;3709(yas/protect-escapes nil '(?\\ ?` ?'))3710;; replace all backquoted expressions3711;;3712(goto-char parse-start)3713(yas/replace-backquotes)3714;; protect escapes again since previous steps might have generated3715;; more characters needing escaping3716;;3717(goto-char parse-start)3718(yas/protect-escapes)3719;; parse fields with {}3720;;3721(goto-char parse-start)3722(yas/field-parse-create snippet)3723;; parse simple mirrors and fields3724;;3725(goto-char parse-start)3726(yas/simple-mirror-parse-create snippet)3727;; parse mirror transforms3728;;3729(goto-char parse-start)3730(yas/transform-mirror-parse-create snippet)3731;; calculate adjacencies of fields and mirrors3732;;3733(yas/calculate-adjacencies snippet)3734;; Delete $-constructs3735;;3736(yas/delete-regions yas/dollar-regions)3737;; restore escapes3738;;3739(goto-char parse-start)3740(yas/restore-escapes)3741;; update mirrors for the first time3742;;3743(yas/update-mirrors snippet)3744;; indent the best we can3745;;3746(goto-char parse-start)3747(yas/indent snippet)))37483749(defun yas/indent-according-to-mode (snippet-markers)3750"Indent current line according to mode, preserving3751SNIPPET-MARKERS."3752;;; Apropos indenting problems....3753;;3754;; `indent-according-to-mode' uses whatever `indent-line-function'3755;; is available. Some implementations of these functions delete text3756;; before they insert. If there happens to be a marker just after3757;; the text being deleted, the insertion actually happens after the3758;; marker, which misplaces it.3759;;3760;; This would also happen if we had used overlays with the3761;; `front-advance' property set to nil.3762;;3763;; This is why I have these `trouble-markers', they are the ones at3764;; they are the ones at the first non-whitespace char at the line3765;; (i.e. at `yas/real-line-beginning'. After indentation takes place3766;; we should be at the correct to restore them to. All other3767;; non-trouble-markers have been *pushed* and don't need special3768;; attention.3769;;3770(goto-char (yas/real-line-beginning))3771(let ((trouble-markers (remove-if-not #'(lambda (marker)3772(= marker (point)))3773snippet-markers)))3774(save-restriction3775(widen)3776(condition-case err3777(indent-according-to-mode)3778(error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)3779nil)))3780(mapc #'(lambda (marker)3781(set-marker marker (point)))3782trouble-markers)))37833784(defvar yas/indent-original-column nil)3785(defun yas/indent (snippet)3786(let ((snippet-markers (yas/collect-snippet-markers snippet)))3787;; Look for those $>3788(save-excursion3789(while (re-search-forward "$>" nil t)3790(delete-region (match-beginning 0) (match-end 0))3791(when (not (eq yas/indent-line 'auto))3792(yas/indent-according-to-mode snippet-markers))))3793;; Now do stuff for 'fixed and 'auto3794(save-excursion3795(cond ((eq yas/indent-line 'fixed)3796(while (and (zerop (forward-line))3797(zerop (current-column)))3798(indent-to-column yas/indent-original-column)))3799((eq yas/indent-line 'auto)3800(let ((end (set-marker (make-marker) (point-max)))3801(indent-first-line-p yas/also-auto-indent-first-line))3802(while (and (zerop (if indent-first-line-p3803(prog13804(forward-line 0)3805(setq indent-first-line-p nil))3806(forward-line 1)))3807(not (eobp))3808(<= (point) end))3809(yas/indent-according-to-mode snippet-markers))))3810(t3811nil)))))38123813(defun yas/collect-snippet-markers (snippet)3814"Make a list of all the markers used by SNIPPET."3815(let (markers)3816(dolist (field (yas/snippet-fields snippet))3817(push (yas/field-start field) markers)3818(push (yas/field-end field) markers)3819(dolist (mirror (yas/field-mirrors field))3820(push (yas/mirror-start mirror) markers)3821(push (yas/mirror-end mirror) markers)))3822(let ((snippet-exit (yas/snippet-exit snippet)))3823(when (and snippet-exit3824(marker-buffer (yas/exit-marker snippet-exit)))3825(push (yas/exit-marker snippet-exit) markers)))3826markers))38273828(defun yas/real-line-beginning ()3829(let ((c (char-after (line-beginning-position)))3830(n (line-beginning-position)))3831(while (or (eql c ?\ )3832(eql c ?\t))3833(incf n)3834(setq c (char-after n)))3835n))38363837(defun yas/escape-string (escaped)3838(concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))38393840(defun yas/protect-escapes (&optional text escaped)3841"Protect all escaped characters with their numeric ASCII value.38423843With optional string TEXT do it in string instead of buffer."3844(let ((changed-text text)3845(text-provided-p text))3846(mapc #'(lambda (escaped)3847(setq changed-text3848(yas/replace-all (concat "\\" (char-to-string escaped))3849(yas/escape-string escaped)3850(when text-provided-p changed-text))))3851(or escaped yas/escaped-characters))3852changed-text))38533854(defun yas/restore-escapes (&optional text escaped)3855"Restore all escaped characters from their numeric ASCII value.38563857With optional string TEXT do it in string instead of the buffer."3858(let ((changed-text text)3859(text-provided-p text))3860(mapc #'(lambda (escaped)3861(setq changed-text3862(yas/replace-all (yas/escape-string escaped)3863(char-to-string escaped)3864(when text-provided-p changed-text))))3865(or escaped yas/escaped-characters))3866changed-text))38673868(defun yas/replace-backquotes ()3869"Replace all the \"`(lisp-expression)`\"-style expression3870with their evaluated value"3871(while (re-search-forward yas/backquote-lisp-expression-regexp nil t)3872(let ((current-string (match-string 1)) transformed)3873(delete-region (match-beginning 0) (match-end 0))3874(setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))3875(goto-char (match-beginning 0))3876(when transformed (insert transformed)))))38773878(defun yas/scan-sexps (from count)3879(condition-case err3880(with-syntax-table (standard-syntax-table)3881(scan-sexps from count))3882(error3883nil)))38843885(defun yas/make-marker (pos)3886"Create a marker at POS with `nil' `marker-insertion-type'"3887(let ((marker (set-marker (make-marker) pos)))3888(set-marker-insertion-type marker nil)3889marker))38903891(defun yas/field-parse-create (snippet &optional parent-field)3892"Parse most field expressions, except for the simple one \"$n\".38933894The following count as a field:38953896* \"${n: text}\", for a numbered field with default text, as long as N is not 0;38973898* \"${n: text$(expression)}, the same with a lisp expression;3899this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'39003901* the same as above but unnumbered, (no N:) and number is calculated automatically.39023903When multiple expressions are found, only the last one counts."3904;;3905(save-excursion3906(while (re-search-forward yas/field-regexp nil t)3907(let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))3908(number (and (match-string-no-properties 1)3909(string-to-number (match-string-no-properties 1))))3910(brand-new-field (and real-match-end-03911;; break if on "$(" immediately3912;; after the ":", this will be3913;; caught as a mirror with3914;; transform later.3915(not (save-match-data3916(eq (string-match "$[ \t\n]*("3917(match-string-no-properties 2)) 0)))3918;; allow ${0: some exit text}3919;; (not (and number (zerop number)))3920(yas/make-field number3921(yas/make-marker (match-beginning 2))3922(yas/make-marker (1- real-match-end-0))3923parent-field))))3924(when brand-new-field3925(goto-char real-match-end-0)3926(push (cons (1- real-match-end-0) real-match-end-0)3927yas/dollar-regions)3928(push (cons (match-beginning 0) (match-beginning 2))3929yas/dollar-regions)3930(push brand-new-field (yas/snippet-fields snippet))3931(save-excursion3932(save-restriction3933(narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))3934(goto-char (point-min))3935(yas/field-parse-create snippet brand-new-field)))))))3936;; if we entered from a parent field, now search for the3937;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for3938;; primary field transformations3939;;3940(when parent-field3941(save-excursion3942(while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)3943(let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))3944;; commit the primary field transformation if:3945;;3946;; 1. we don't find it in yas/dollar-regions (a subnested3947;; field) might have already caught it.3948;;3949;; 2. we really make sure we have either two '$' or some3950;; text and a '$' after the colon ':'. This is a FIXME: work3951;; my regular expressions and end these ugly hacks.3952;;3953(when (and real-match-end-13954(not (member (cons (match-beginning 0)3955real-match-end-1)3956yas/dollar-regions))3957(not (eq ?:3958(char-before (1- (match-beginning 1))))))3959(let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)3960real-match-end-1)))3961(setf (yas/field-transform parent-field)3962(yas/read-lisp (yas/restore-escapes lisp-expression-string))))3963(push (cons (match-beginning 0) real-match-end-1)3964yas/dollar-regions)))))))39653966(defun yas/transform-mirror-parse-create (snippet)3967"Parse the \"${n:$(lisp-expression)}\" mirror transformations."3968(while (re-search-forward yas/transform-mirror-regexp nil t)3969(let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))3970(number (string-to-number (match-string-no-properties 1)))3971(field (and number3972(not (zerop number))3973(yas/snippet-find-field snippet number)))3974(brand-new-mirror3975(and real-match-end-03976field3977(yas/make-mirror (yas/make-marker (match-beginning 0))3978(yas/make-marker (match-beginning 0))3979(yas/read-lisp3980(yas/restore-escapes3981(buffer-substring-no-properties (match-beginning 2)3982(1- real-match-end-0))))))))3983(when brand-new-mirror3984(push brand-new-mirror3985(yas/field-mirrors field))3986(yas/calculate-mirrors-in-fields snippet brand-new-mirror)3987(push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))39883989(defun yas/simple-mirror-parse-create (snippet)3990"Parse the simple \"$n\" fields/mirrors/exitmarkers."3991(while (re-search-forward yas/simple-mirror-regexp nil t)3992(let ((number (string-to-number (match-string-no-properties 1))))3993(cond ((zerop number)39943995(setf (yas/snippet-exit snippet)3996(yas/make-exit (yas/make-marker (match-end 0))))3997(save-excursion3998(goto-char (match-beginning 0))3999(when yas/wrap-around-region4000(cond (yas/selected-text4001(insert yas/selected-text))4002((and (eq yas/wrap-around-region 'cua)4003cua-mode4004(get-register ?0))4005(insert (prog1 (get-register ?0)4006(set-register ?0 nil))))))4007(push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))4008yas/dollar-regions)))4009(t4010(let ((field (yas/snippet-find-field snippet number)))4011(if field4012(let ((brand-new-mirror (yas/make-mirror4013(yas/make-marker (match-beginning 0))4014(yas/make-marker (match-beginning 0))4015nil)))4016(push brand-new-mirror4017(yas/field-mirrors field))4018(yas/calculate-mirrors-in-fields snippet brand-new-mirror))4019(push (yas/make-field number4020(yas/make-marker (match-beginning 0))4021(yas/make-marker (match-beginning 0))4022nil)4023(yas/snippet-fields snippet))))4024(push (cons (match-beginning 0) (match-end 0))4025yas/dollar-regions))))))40264027(defun yas/delete-regions (regions)4028"Sort disjuct REGIONS by start point, then delete from the back."4029(mapc #'(lambda (reg)4030(delete-region (car reg) (cdr reg)))4031(sort regions4032#'(lambda (r1 r2)4033(>= (car r1) (car r2))))))40344035(defun yas/update-mirrors (snippet)4036"Updates all the mirrors of SNIPPET."4037(save-excursion4038(let* ((fields (copy-list (yas/snippet-fields snippet)))4039(field (car fields)))4040(while field4041(dolist (mirror (yas/field-mirrors field))4042;; stacked expansion: I added an `inhibit-modification-hooks'4043;; here, for safety, may need to remove if we the mechanism is4044;; altered.4045;;4046(let ((inhibit-modification-hooks t)4047(mirror-parent-field (yas/mirror-parent-field mirror)))4048;; updatte this mirror4049;;4050(yas/mirror-update-display mirror field)4051;; for mirrors-in-fields: schedule a possible4052;; parent field for reupdting later on4053;;4054(when mirror-parent-field4055(add-to-list 'fields mirror-parent-field 'append #'eq))4056;; `yas/place-overlays' is needed if the active field and4057;; protected overlays have been changed because of insertions4058;; in `yas/mirror-update-display'4059;;4060(when (eq field (yas/snippet-active-field snippet))4061(yas/place-overlays snippet field))))4062(setq fields (cdr fields))4063(setq field (car fields))))))40644065(defun yas/mirror-update-display (mirror field)4066"Update MIRROR according to FIELD (and mirror transform)."40674068(let* ((mirror-parent-field (yas/mirror-parent-field mirror))4069(reflection (and (not (and mirror-parent-field4070(yas/field-modified-p mirror-parent-field)))4071(or (yas/apply-transform mirror field 'empty-on-nil)4072(yas/field-text-for-display field)))))4073(when (and reflection4074(not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)4075(yas/mirror-end mirror)))))4076(goto-char (yas/mirror-start mirror))4077(insert reflection)4078(if (> (yas/mirror-end mirror) (point))4079(delete-region (point) (yas/mirror-end mirror))4080(set-marker (yas/mirror-end mirror) (point))4081(yas/advance-start-maybe (yas/mirror-next mirror) (point))4082;; super-special advance4083(yas/advance-end-of-parents-maybe mirror-parent-field (point))))))40844085(defun yas/field-update-display (field snippet)4086"Much like `yas/mirror-update-display', but for fields"4087(when (yas/field-transform field)4088(let ((inhibit-modification-hooks t)4089(transformed (and (not (eq (yas/field-number field) 0))4090(yas/apply-transform field field)))4091(point (point)))4092(when (and transformed4093(not (string= transformed (buffer-substring-no-properties (yas/field-start field)4094(yas/field-end field)))))4095(setf (yas/field-modified-p field) t)4096(goto-char (yas/field-start field))4097(insert transformed)4098(if (> (yas/field-end field) (point))4099(delete-region (point) (yas/field-end field))4100(set-marker (yas/field-end field) (point))4101(yas/advance-start-maybe (yas/field-next field) (point)))4102t))))410341044105;;; Pre- and post-command hooks:41064107(defvar yas/post-command-runonce-actions nil4108"List of actions to run once `post-command-hook'.41094110Each element of this list looks like (FN . ARGS) where FN is4111called with ARGS as its arguments after the currently executing4112snippet command.41134114After all actions have been run, this list is emptied, and after4115that the rest of `yas/post-command-handler' runs.")41164117(defun yas/pre-command-handler () )41184119(defun yas/post-command-handler ()4120"Handles various yasnippet conditions after each command."4121(when yas/post-command-runonce-actions4122(condition-case err4123(mapc #'(lambda (fn-and-args)4124(apply (car fn-and-args)4125(cdr fn-and-args)))4126yas/post-command-runonce-actions)4127(error (message "[yas] problem running `yas/post-command-runonce-actions'!")))4128(setq yas/post-command-runonce-actions nil))4129(cond (yas/protection-violation4130(goto-char yas/protection-violation)4131(setq yas/protection-violation nil))4132((eq 'undo this-command)4133;;4134;; After undo revival the correct field is sometimes not4135;; restored correctly, this condition handles that4136;;4137(let* ((snippet (car (yas/snippets-at-point)))4138(target-field (and snippet4139(find-if-not #'(lambda (field)4140(yas/field-probably-deleted-p snippet field))4141(remove nil4142(cons (yas/snippet-active-field snippet)4143(yas/snippet-fields snippet)))))))4144(when target-field4145(yas/move-to-field snippet target-field))))4146((not (yas/undo-in-progress))4147;; When not in an undo, check if we must commit the snippet4148;; (user exited it).4149(yas/check-commit-snippet))))41504151;;; Fancy docs:41524153(put 'yas/expand 'function-documentation4154'(yas/expand-from-trigger-key-doc))4155(defun yas/expand-from-trigger-key-doc ()4156"A doc synthethizer for `yas/expand-from-trigger-key-doc'."4157(let ((fallback-description4158(cond ((eq yas/fallback-behavior 'call-other-command)4159(let* ((yas/minor-mode nil)4160(fallback (key-binding (read-kbd-macro yas/trigger-key))))4161(or (and fallback4162(format " call command `%s'." (pp-to-string fallback)))4163" do nothing.")))4164((eq yas/fallback-behavior 'return-nil)4165", do nothing.")4166(t4167", defer to `yas/fallback-behaviour' :-)"))))4168(concat "Expand a snippet before point. If no snippet4169expansion is possible,"4170fallback-description4171"\n\nOptional argument FIELD is for non-interactive use and is an4172object satisfying `yas/field-p' to restrict the expansion to.")))41734174(put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))4175(defun yas/expand-from-keymap-doc ()4176"A doc synthethizer for `yas/expand-from-keymap-doc'."4177(add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)4178(concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"4179(when (eq this-command 'describe-key)4180(let* ((vec (this-single-command-keys))4181(templates (mapcan #'(lambda (table)4182(yas/fetch table vec))4183(yas/get-snippet-tables)))4184(yas/direct-keymaps nil)4185(fallback (key-binding vec)))4186(concat "In this case, "4187(when templates4188(concat "these snippets are bound to this key:\n"4189(yas/template-pretty-list templates)4190"\n\nIf none of these expands, "))4191(or (and fallback4192(format "fallback `%s' will be called." (pp-to-string fallback)))4193"no fallback keybinding is called."))))))41944195(defun yas/template-pretty-list (templates)4196(let ((acc)4197(yas/buffer-local-condition 'always))4198(dolist (plate templates)4199(setq acc (concat acc "\n*) "4200(propertize (concat "\\\\snippet `" (car plate) "'")4201'yasnippet (cdr plate)))))4202acc))42034204(define-button-type 'help-snippet-def4205:supertype 'help-xref4206'help-function (lambda (template) (yas/visit-snippet-file-1 template))4207'help-echo (purecopy "mouse-2, RET: find snippets's definition"))42084209(defun yas/snippet-description-finish-runonce ()4210"Final adjustments for the help buffer when snippets are concerned."4211(yas/create-snippet-xrefs)4212(remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))42134214(defun yas/create-snippet-xrefs ()4215(save-excursion4216(goto-char (point-min))4217(while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)4218(let ((template (get-text-property (match-beginning 1)4219'yasnippet)))4220(when template4221(help-xref-button 1 'help-snippet-def template)4222(kill-region (match-end 1) (match-end 0))4223(kill-region (match-beginning 0) (match-beginning 1)))))))42244225(defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)4226"Expand a snippet registered in MODE-SYMBOL's table with UUID.42274228Remaining args as in `yas/expand-snippet'."4229(let* ((table (gethash mode-symbol yas/tables))4230(yas/current-template (and table4231(gethash uuid (yas/table-uuidhash table)))))4232(when yas/current-template4233(yas/expand-snippet (yas/template-content yas/current-template)))))423442354236;;; Some hacks:4237;; `locate-dominating-file' is added for compatibility in emacs < 234238(unless (or (eq emacs-major-version 23)4239(fboundp 'locate-dominating-file))4240(defvar locate-dominating-stop-dir-regexp4241"\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"4242"Regexp of directory names which stop the search in `locate-dominating-file'.4243Any directory whose name matches this regexp will be treated like4244a kind of root directory by `locate-dominating-file' which will stop its search4245when it bumps into it.4246The default regexp prevents fruitless and time-consuming attempts to find4247special files in directories in which filenames are interpreted as hostnames,4248or mount points potentially requiring authentication as a different user.")42494250(defun locate-dominating-file (file name)4251"Look up the directory hierarchy from FILE for a file named NAME.4252Stop at the first parent directory containing a file NAME,4253and return the directory. Return nil if not found."4254;; We used to use the above locate-dominating-files code, but the4255;; directory-files call is very costly, so we're much better off doing4256;; multiple calls using the code in here.4257;;4258;; Represent /home/luser/foo as ~/foo so that we don't try to look for4259;; `name' in /home or in /.4260(setq file (abbreviate-file-name file))4261(let ((root nil)4262(prev-file file)4263;; `user' is not initialized outside the loop because4264;; `file' may not exist, so we may have to walk up part of the4265;; hierarchy before we find the "initial UUID".4266(user nil)4267try)4268(while (not (or root4269(null file)4270;; FIXME: Disabled this heuristic because it is sometimes4271;; inappropriate.4272;; As a heuristic, we stop looking up the hierarchy of4273;; directories as soon as we find a directory belonging4274;; to another user. This should save us from looking in4275;; things like /net and /afs. This assumes that all the4276;; files inside a project belong to the same user.4277;; (let ((prev-user user))4278;; (setq user (nth 2 (file-attributes file)))4279;; (and prev-user (not (equal user prev-user))))4280(string-match locate-dominating-stop-dir-regexp file)))4281(setq try (file-exists-p (expand-file-name name file)))4282(cond (try (setq root file))4283((equal file (setq prev-file file4284file (file-name-directory4285(directory-file-name file))))4286(setq file nil))))4287root)))42884289;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error4290;; (when it execute forward-char) and interrupt the after change4291;; hook. Thus prevent the insert-behind hook of yasnippet to be4292;; invoked. Here's a way to reproduce it:42934294;; # open a *new* Emacs.4295;; # load yasnippet.4296;; # open a *new* .cpp file.4297;; # input "inc" and press TAB to expand the snippet.4298;; # select the `#include <...>` snippet.4299;; # type inside `<>`43004301(defadvice c-neutralize-syntax-in-CPP4302(around yas-mp/c-neutralize-syntax-in-CPP activate)4303"Adviced `c-neutralize-syntax-in-CPP' to properly4304handle the end-of-buffer error fired in it by calling4305`forward-char' at the end of buffer."4306(condition-case err4307ad-do-it4308(error (message (error-message-string err)))))43094310;; disable c-electric-* serial command in YAS fields4311(add-hook 'c-mode-common-hook4312'(lambda ()4313(dolist (k '(":" ">" ";" "<" "{" "}"))4314(define-key (symbol-value (make-local-variable 'yas/keymap))4315k 'self-insert-command))))43164317(provide 'yasnippet)43184319;;; yasnippet.el ends here432043214322