]> code.delx.au - gnu-emacs-elpa/blob - yasnippet.el
* Fix some stacked expansion bugs (snippet-in-snippet)
[gnu-emacs-elpa] / yasnippet.el
1 ;;; Yasnippet.el --- Yet another snippet extension for Emacs.
2
3 ;; Copyright 2008 pluskid
4 ;; 2009 pluskid, joaotavora
5
6 ;; Authors: pluskid <pluskid@gmail.com>, joaotavora <joaotavora@gmail.com>
7 ;; Version: 0.7.0
8 ;; Package-version: 0.7.0
9 ;; X-URL: http://code.google.com/p/yasnippet/
10 ;; Keywords: convenience, emulation
11 ;; URL: http://code.google.com/p/yasnippet/
12 ;; EmacsWiki: YaSnippetMode
13
14 ;; This file is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; This file is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING. If not, write to
26 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; Basic steps to setup:
32 ;;
33 ;; 1. In your .emacs file:
34 ;; (add-to-list 'load-path "/dir/to/yasnippet.el")
35 ;; (require 'yasnippet)
36 ;; 2. Place the `snippets' directory somewhere. E.g: ~/.emacs.d/snippets
37 ;; 3. In your .emacs file
38 ;; (setq yas/snippet-dirs "~/.emacs/snippets")
39 ;; (yas/load-directory yas/snippet-dirs)
40 ;; 4. To enable the YASnippet menu and tab-trigger expansion
41 ;; M-x yas/minor-mode
42 ;; 5. To globally enable the minor mode in *all* buffers
43 ;; M-x yas/global-mode
44 ;;
45 ;; Steps 4. and 5. are optional, you don't have to use the minor
46 ;; mode to use YASnippet.
47 ;;
48 ;; Interesting variables are:
49 ;;
50 ;; `yas/snippet-dirs'
51 ;;
52 ;; The directory where user-created snippets are to be
53 ;; stored. Can also be a list of directories. In that case,
54 ;; when used for bulk (re)loading of snippets (at startup or
55 ;; via `yas/reload-all'), directories appearing earlier in
56 ;; the list shadow other dir's snippets. Also, the first
57 ;; directory is taken as the default for storing the user's
58 ;; new snippets.
59 ;;
60 ;; The deprecated `yas/root-directory' aliases this variable
61 ;; for backward-compatibility.
62 ;;
63 ;; `yas/extra-modes'
64 ;;
65 ;; A local variable that you can set in a hook to override
66 ;; snippet-lookup based on major mode. It is a a symbol (or
67 ;; list of symbols) that correspond to subdirectories of
68 ;; `yas/snippet-dirs' and is used for deciding which
69 ;; snippets to consider for the active buffer.
70 ;;
71 ;; Deprecated `yas/mode-symbol' aliases this variable for
72 ;; backward-compatibility.
73 ;;
74 ;; Major commands are:
75 ;;
76 ;; M-x yas/expand
77 ;;
78 ;; Try to expand snippets before point. In `yas/minor-mode',
79 ;; this is bound to `yas/trigger-key' which you can customize.
80 ;;
81 ;; M-x yas/load-directory
82 ;;
83 ;; Prompts you for a directory hierarchy of snippets to load.
84 ;;
85 ;; M-x yas/insert-snippet
86 ;;
87 ;; Prompts you for possible snippet expansion if that is
88 ;; possible according to buffer-local and snippet-local
89 ;; expansion conditions. With prefix argument, ignore these
90 ;; conditions.
91 ;;
92 ;; M-x yas/find-snippets
93 ;;
94 ;; Lets you find the snippet files in the correct
95 ;; subdirectory of `yas/snippet-dirs', according to the
96 ;; active major mode (if it exists) like
97 ;; `find-file-other-window'.
98 ;;
99 ;; M-x yas/visit-snippet-file
100 ;;
101 ;; Prompts you for possible snippet expansions like
102 ;; `yas/insert-snippet', but instead of expanding it, takes
103 ;; you directly to the snippet definition's file, if it
104 ;; exists.
105 ;;
106 ;; M-x yas/new-snippet
107 ;;
108 ;; Lets you create a new snippet file in the correct
109 ;; subdirectory of `yas/snippet-dirs', according to the
110 ;; active major mode.
111 ;;
112 ;; M-x yas/load-snippet-buffer
113 ;;
114 ;; When editing a snippet, this loads the snippet. This is
115 ;; bound to "C-c C-c" while in the `snippet-mode' editing
116 ;; mode.
117 ;;
118 ;; M-x yas/tryout-snippet
119 ;;
120 ;; When editing a snippet, this opens a new empty buffer,
121 ;; sets it to the appropriate major mode and inserts the
122 ;; snippet there, so you can see what it looks like. This is
123 ;; bound to "C-c C-t" while in `snippet-mode'.
124 ;;
125 ;; M-x yas/describe-tables
126 ;;
127 ;; Lists known snippets in a separate buffer. User is
128 ;; prompted as to whether only the currently active tables
129 ;; are to be displayed, or all the tables for all major
130 ;; modes.
131 ;;
132 ;; The `dropdown-list.el' extension is bundled with YASnippet, you
133 ;; can optionally use it the preferred "prompting method", puting in
134 ;; your .emacs file, for example:
135 ;;
136 ;; (require 'dropdown-list)
137 ;; (setq yas/prompt-functions '(yas/dropdown-prompt
138 ;; yas/ido-prompt
139 ;; yas/completing-prompt))
140 ;;
141 ;; Also check out the customization group
142 ;;
143 ;; M-x customize-group RET yasnippet RET
144 ;;
145 ;; If you use the customization group to set variables
146 ;; `yas/snippet-dirs' or `yas/global-mode', make sure the path to
147 ;; "yasnippet.el" is present in the `load-path' *before* the
148 ;; `custom-set-variables' is executed in your .emacs file.
149 ;;
150 ;; For more information and detailed usage, refer to the project page:
151 ;; http://code.google.com/p/yasnippet/
152
153 ;;; Code:
154
155 (require 'cl)
156 (require 'assoc)
157 (require 'easymenu)
158 (require 'help-mode)
159
160 \f
161 ;;; User customizable variables
162
163 (defgroup yasnippet nil
164 "Yet Another Snippet extension"
165 :group 'editing)
166
167 ;;;###autoload
168 (defcustom yas/snippet-dirs nil
169 "Directory or list of snippet dirs for each major mode.
170
171 The directory where user-created snippets are to be stored. Can
172 also be a list of directories. In that case, when used for
173 bulk (re)loading of snippets (at startup or via
174 `yas/reload-all'), directories appearing earlier in the list
175 shadow other dir's snippets. Also, the first directory is taken
176 as the default for storing the user's new snippets."
177 :type '(choice (string :tag "Single directory (string)")
178 (repeat :args (string) :tag "List of directories (strings)"))
179 :group 'yasnippet
180 :require 'yasnippet
181 :set #'(lambda (symbol new)
182 (let ((old (and (boundp symbol)
183 (symbol-value symbol))))
184 (set-default symbol new)
185 (unless (or (not (fboundp 'yas/reload-all))
186 (equal old new))
187 (yas/reload-all)))))
188 (defun yas/snippet-dirs ()
189 (if (listp yas/snippet-dirs) yas/snippet-dirs (list yas/snippet-dirs)))
190 (defvaralias 'yas/root-directory 'yas/snippet-dirs)
191
192 (defcustom yas/prompt-functions '(yas/x-prompt
193 yas/dropdown-prompt
194 yas/completing-prompt
195 yas/ido-prompt
196 yas/no-prompt)
197 "Functions to prompt for keys, templates, etc interactively.
198
199 These functions are called with the following arguments:
200
201 - PROMPT: A string to prompt the user
202
203 - CHOICES: a list of strings or objects.
204
205 - optional DISPLAY-FN : A function that, when applied to each of
206 the objects in CHOICES will return a string.
207
208 The return value of any function you put here should be one of
209 the objects in CHOICES, properly formatted with DISPLAY-FN (if
210 that is passed).
211
212 - To signal that your particular style of prompting is
213 unavailable at the moment, you can also have the function return
214 nil.
215
216 - To signal that the user quit the prompting process, you can
217 signal `quit' with
218
219 (signal 'quit \"user quit!\")."
220 :type '(repeat function)
221 :group 'yasnippet)
222
223 (defcustom yas/indent-line 'auto
224 "Controls indenting applied to a recent snippet expansion.
225
226 The following values are possible:
227
228 - `fixed' Indent the snippet to the current column;
229
230 - `auto' Indent each line of the snippet with `indent-according-to-mode'
231
232 Every other value means don't apply any snippet-side indendation
233 after expansion (the manual per-line \"$>\" indentation still
234 applies)."
235 :type '(choice (const :tag "Nothing" nothing)
236 (const :tag "Fixed" fixed)
237 (const :tag "Auto" auto))
238 :group 'yasnippet)
239
240 (defcustom yas/also-auto-indent-first-line nil
241 "Non-nil means also auto indent first line according to mode.
242
243 Naturally this is only valid when `yas/indent-line' is `auto'"
244 :type 'boolean
245 :group 'yasnippet)
246
247 (defcustom yas/snippet-revival t
248 "Non-nil means re-activate snippet fields after undo/redo."
249 :type 'boolean
250 :group 'yasnippet)
251
252 (defcustom yas/trigger-key "TAB"
253 "The key bound to `yas/expand' when function `yas/minor-mode' is active.
254
255 Value is a string that is converted to the internal Emacs key
256 representation using `read-kbd-macro'."
257 :type 'string
258 :group 'yasnippet
259 :set #'(lambda (symbol key)
260 (let ((old (and (boundp symbol)
261 (symbol-value symbol))))
262 (set-default symbol key)
263 ;; On very first loading of this defcustom,
264 ;; `yas/trigger-key' is *not* loaded.
265 (if (fboundp 'yas/trigger-key-reload)
266 (yas/trigger-key-reload old)))))
267
268 (defcustom yas/next-field-key '("TAB" "<tab>")
269 "The key to navigate to next field when a snippet is active.
270
271 Value is a string that is converted to the internal Emacs key
272 representation using `read-kbd-macro'.
273
274 Can also be a list of strings."
275 :type '(choice (string :tag "String")
276 (repeat :args (string) :tag "List of strings"))
277 :group 'yasnippet
278 :set #'(lambda (symbol val)
279 (set-default symbol val)
280 (if (fboundp 'yas/init-yas-in-snippet-keymap)
281 (yas/init-yas-in-snippet-keymap))))
282
283
284 (defcustom yas/prev-field-key '("<backtab>" "<S-tab>")
285 "The key to navigate to previous field when a snippet is active.
286
287 Value is a string that is converted to the internal Emacs key
288 representation using `read-kbd-macro'.
289
290 Can also be a list of strings."
291 :type '(choice (string :tag "String")
292 (repeat :args (string) :tag "List of strings"))
293 :group 'yasnippet
294 :set #'(lambda (symbol val)
295 (set-default symbol val)
296 (if (fboundp 'yas/init-yas-in-snippet-keymap)
297 (yas/init-yas-in-snippet-keymap))))
298
299 (defcustom yas/skip-and-clear-key "C-d"
300 "The key to clear the currently active field.
301
302 Value is a string that is converted to the internal Emacs key
303 representation using `read-kbd-macro'.
304
305 Can also be a list of strings."
306 :type '(choice (string :tag "String")
307 (repeat :args (string) :tag "List of strings"))
308 :group 'yasnippet
309 :set #'(lambda (symbol val)
310 (set-default symbol val)
311 (if (fboundp 'yas/init-yas-in-snippet-keymap)
312 (yas/init-yas-in-snippet-keymap))))
313
314 (defcustom yas/triggers-in-field nil
315 "If non-nil, `yas/next-field-key' can trigger stacked expansions.
316
317 Otherwise, `yas/next-field-key' just tries to move on to the next
318 field"
319 :type 'boolean
320 :group 'yasnippet)
321
322 (defcustom yas/fallback-behavior 'call-other-command
323 "How to act when `yas/trigger-key' does *not* expand a snippet.
324
325 - `call-other-command' means try to temporarily disable YASnippet
326 and call the next command bound to `yas/trigger-key'.
327
328 - nil or the symbol `return-nil' mean do nothing. (and
329 `yas/expand-returns' nil)
330
331 - A lisp form (apply COMMAND . ARGS) means interactively call
332 COMMAND, if ARGS is non-nil, call COMMAND non-interactively
333 with ARGS as arguments."
334 :type '(choice (const :tag "Call previous command" call-other-command)
335 (const :tag "Do nothing" return-nil))
336 :group 'yasnippet)
337
338 (defcustom yas/choose-keys-first nil
339 "If non-nil, prompt for snippet key first, then for template.
340
341 Otherwise prompts for all possible snippet names.
342
343 This affects `yas/insert-snippet' and `yas/visit-snippet-file'."
344 :type 'boolean
345 :group 'yasnippet)
346
347 (defcustom yas/choose-tables-first nil
348 "If non-nil, and multiple eligible snippet tables, prompts user for tables first.
349
350 Otherwise, user chooses between the merging together of all
351 eligible tables.
352
353 This affects `yas/insert-snippet', `yas/visit-snippet-file'"
354 :type 'boolean
355 :group 'yasnippet)
356
357 (defcustom yas/use-menu 'abbreviate
358 "Display a YASnippet menu in the menu bar.
359
360 When non-nil, submenus for each snippet table will be listed
361 under the menu \"Yasnippet\".
362
363 - If set to `real-modes' only submenus whose name more or less
364 corresponds to a major mode are listed.
365
366 - If set to `abbreviate', only the current major-mode
367 menu and the modes set in `yas/extra-modes' are listed.
368
369 Any other non-nil value, every submenu is listed."
370 :type '(choice (const :tag "Full" t)
371 (const :tag "Real modes only" real-modes)
372 (const :tag "Abbreviate" abbreviate))
373 :group 'yasnippet)
374
375 (defcustom yas/trigger-symbol " =>"
376 "The text that will be used in menu to represent the trigger."
377 :type 'string
378 :group 'yasnippet)
379
380 (defcustom yas/wrap-around-region nil
381 "If non-nil, snippet expansion wraps around selected region.
382
383 The wrapping occurs just before the snippet's exit marker. This
384 can be overriden on a per-snippet basis."
385 :type 'boolean
386 :group 'yasnippet)
387
388 (defcustom yas/good-grace t
389 "If non-nil, don't raise errors in inline elisp evaluation.
390
391 An error string \"[yas] error\" is returned instead."
392 :type 'boolean
393 :group 'yasnippet)
394
395 (defcustom yas/ignore-filenames-as-triggers nil
396 "If non-nil, don't derive tab triggers from filenames.
397
398 This means a snippet without a \"# key:'\ directive won't have a
399 tab trigger."
400 :type 'boolean
401 :group 'yasnippet)
402
403 (defcustom yas/visit-from-menu nil
404 "If non-nil visit snippets's files from menu, instead of expanding them.
405
406 This cafn only work when snippets are loaded from files."
407 :type 'boolean
408 :group 'yasnippet)
409
410 (defcustom yas/expand-only-for-last-commands nil
411 "List of `last-command' values to restrict tab-triggering to, or nil.
412
413 Leave this set at nil (the default) to be able to trigger an
414 expansion simply by placing the cursor after a valid tab trigger,
415 using whichever commands.
416
417 Optionallly, set this to something like '(self-insert-command) if
418 you to wish restrict expansion to only happen when the last
419 letter of the snippet tab trigger was typed immediately before
420 the trigger key itself."
421 :type '(repeat function)
422 :group 'yasnippet)
423
424 ;; Only two faces, and one of them shouldn't even be used...
425 ;;
426 (defface yas/field-highlight-face
427 '((t (:inherit 'region)))
428 "The face used to highlight the currently active field of a snippet"
429 :group 'yasnippet)
430
431 (defface yas/field-debug-face
432 '()
433 "The face used for debugging some overlays normally hidden"
434 :group 'yasnippet)
435
436 \f
437 ;;; User can also customize the next defvars
438 (defun yas/define-some-keys (keys keymap definition)
439 "Bind KEYS to DEFINITION in KEYMAP, read with `read-kbd-macro'."
440 (let ((keys (or (and (listp keys) keys)
441 (list keys))))
442 (dolist (key keys)
443 (define-key keymap (read-kbd-macro key) definition))))
444
445 (defvar yas/keymap
446 (let ((map (make-sparse-keymap)))
447 (mapc #'(lambda (binding)
448 (yas/define-some-keys (car binding) map (cdr binding)))
449 `((,yas/next-field-key . yas/next-field-or-maybe-expand)
450 (,yas/prev-field-key . yas/prev-field)
451 ("C-g" . yas/abort-snippet)
452 (,yas/skip-and-clear-key . yas/skip-and-clear-or-delete-char)))
453 map)
454 "The keymap active while a snippet expansion is in progress.")
455
456 (defvar yas/key-syntaxes (list "w" "w_" "w_." "w_.()" "^ ")
457 "List of character syntaxes used to find a trigger key before point.
458 Scanning backwards for a key, this list is tried in the
459 order. For example, if the list is '(\"w\" \"w_\") first look
460 trigger keys which are composed exclusively of \"word\"-syntax
461 characters, and then, if that fails, look for keys which are
462 either of \"word\" or \"symbol\" syntax. So triggering after
463 triggering after:
464
465 foo-bar
466
467 will first try \"bar\", if that trigger key isn't found found,
468 \"foo-bar\" is tried.")
469
470 (defvar yas/after-exit-snippet-hook
471 '()
472 "Hooks to run after a snippet exited.
473
474 The hooks will be run in an environment where some variables bound to
475 proper values:
476
477 `yas/snippet-beg' : The beginning of the region of the snippet.
478
479 `yas/snippet-end' : Similar to beg.
480
481 Attention: These hooks are not run when exiting nested/stackd snippet expansion!")
482
483 (defvar yas/before-expand-snippet-hook
484 '()
485 "Hooks to run just before expanding a snippet.")
486
487 (defvar yas/buffer-local-condition
488 '(if (and (or (fourth (syntax-ppss))
489 (fifth (syntax-ppss)))
490 (eq (symbol-function this-command) 'yas/expand-from-trigger-key))
491 '(require-snippet-condition . force-in-comment)
492 t)
493 "Snippet expanding condition.
494
495 This variable is a lisp form:
496
497 * If it evaluates to nil, no snippets can be expanded.
498
499 * If it evaluates to the a cons (require-snippet-condition
500 . REQUIREMENT)
501
502 * Snippets bearing no \"# condition:\" directive are not
503 considered
504
505 * Snippets bearing conditions that evaluate to nil (or
506 produce an error) won't be onsidered.
507
508 * If the snippet has a condition that evaluates to non-nil
509 RESULT:
510
511 * If REQUIREMENT is t, the snippet is considered
512
513 * If REQUIREMENT is `eq' RESULT, the snippet is
514 considered
515
516 * Otherwise, the snippet is not considered.
517
518 * If it evaluates to the symbol 'always, all snippets are
519 considered for expansion, regardless of any conditions.
520
521 * If it evaluates to t or some other non-nil value
522
523 * Snippet bearing no conditions, or conditions that
524 evaluate to non-nil, are considered for expansion.
525
526 * Otherwise, the snippet is not considered.
527
528 Here's an example preventing snippets from being expanded from
529 inside comments, in `python-mode' only, with the exception of
530 snippets returning the symbol 'force-in-comment in their
531 conditions.
532
533 (add-hook 'python-mode-hook
534 '(lambda ()
535 (setq yas/buffer-local-condition
536 '(if (python-in-string/comment)
537 '(require-snippet-condition . force-in-comment)
538 t))))
539
540 The default value is similar, it filters out potential snippet
541 expansions inside comments and string literals, unless the
542 snippet itself contains a condition that returns the symbol
543 `force-in-comment'.")
544
545 \f
546 ;;; Internal variables
547
548 (defvar yas/version "0.7.0")
549
550 (defvar yas/menu-table (make-hash-table)
551 "A hash table of MAJOR-MODE symbols to menu keymaps.")
552
553 (defun teste ()
554 (interactive)
555 (message "AHAHA!"))
556
557 (defvar yas/known-modes
558 '(ruby-mode rst-mode markdown-mode)
559 "A list of mode which is well known but not part of emacs.")
560
561 (defvar yas/escaped-characters
562 '(?\\ ?` ?' ?$ ?} ?\( ?\))
563 "List of characters which *might* need to be escaped.")
564
565 (defconst yas/field-regexp
566 "${\\([0-9]+:\\)?\\([^}]*\\)}"
567 "A regexp to *almost* recognize a field.")
568
569 (defconst yas/multi-dollar-lisp-expression-regexp
570 "$+[ \t\n]*\\(([^)]*)\\)"
571 "A regexp to *almost* recognize a \"$(...)\" expression.")
572
573 (defconst yas/backquote-lisp-expression-regexp
574 "`\\([^`]*\\)`"
575 "A regexp to recognize a \"`lisp-expression`\" expression." )
576
577 (defconst yas/transform-mirror-regexp
578 "${\\(?:\\([0-9]+\\):\\)?$\\([ \t\n]*([^}]*\\)"
579 "A regexp to *almost* recognize a mirror with a transform.")
580
581 (defconst yas/simple-mirror-regexp
582 "$\\([0-9]+\\)"
583 "A regexp to recognize a simple mirror.")
584
585 (defvar yas/snippet-id-seed 0
586 "Contains the next id for a snippet.")
587
588 (defun yas/snippet-next-id ()
589 (let ((id yas/snippet-id-seed))
590 (incf yas/snippet-id-seed)
591 id))
592
593 \f
594 ;;; Minor mode stuff
595
596 ;; XXX: `last-buffer-undo-list' is somehow needed in Carbon Emacs for MacOSX
597 (defvar last-buffer-undo-list nil)
598
599 (defvar yas/minor-mode-menu nil
600 "Holds the YASnippet menu")
601
602 (defun yas/init-minor-keymap ()
603 (let ((map (make-sparse-keymap)))
604 (easy-menu-define yas/minor-mode-menu
605 map
606 "Menu used when YAS/minor-mode is active."
607 '("YASnippet"
608 "----"
609 ["Expand trigger" yas/expand
610 :help "Possibly expand tab trigger before point"]
611 ["Insert at point..." yas/insert-snippet
612 :help "Prompt for an expandable snippet and expand it at point"]
613 ["New snippet..." yas/new-snippet
614 :help "Create a new snippet in an appropriate directory"]
615 ["Visit snippet file..." yas/visit-snippet-file
616 :help "Prompt for an expandable snippet and find its file"]
617 ["Find snippets..." yas/find-snippets
618 :help "Invoke `find-file' in the appropriate snippet directory"]
619 "----"
620 ("Snippet menu behaviour"
621 ["Visit snippets" (setq yas/visit-from-menu t)
622 :help "Visit snippets from the menu"
623 :active t :style radio :selected yas/visit-from-menu]
624 ["Expand snippets" (setq yas/visit-from-menu nil)
625 :help "Expand snippets from the menu"
626 :active t :style radio :selected (not yas/visit-from-menu)]
627 "----"
628 ["Show \"Real\" modes only" (setq yas/use-menu 'real-modes)
629 :help "Show snippet submenus for modes that appear to be real major modes"
630 :active t :style radio :selected (eq yas/use-menu 'real-modes)]
631 ["Show all modes" (setq yas/use-menu 't)
632 :help "Show one snippet submenu for each loaded table"
633 :active t :style radio :selected (eq yas/use-menu 't)]
634 ["Abbreviate according to current mode" (setq yas/use-menu 'abbreviate)
635 :help "Show only snippet submenus for the current active modes"
636 :active t :style radio :selected (eq yas/use-menu 'abbreviate)])
637 ("Indenting"
638 ["Auto" (setq yas/indent-line 'auto)
639 :help "Indent each line of the snippet with `indent-according-to-mode'"
640 :active t :style radio :selected (eq yas/indent-line 'auto)]
641 ["Fixed" (setq yas/indent-line 'fixed)
642 :help "Indent the snippet to the current column"
643 :active t :style radio :selected (eq yas/indent-line 'fixed)]
644 ["None" (setq yas/indent-line 'none)
645 :help "Don't apply any particular snippet indentation after expansion"
646 :active t :style radio :selected (not (member yas/indent-line '(fixed auto)))]
647 "----"
648 ["Also auto indent first line" (setq yas/also-auto-indent-first-line
649 (not yas/also-auto-indent-first-line))
650 :help "When auto-indenting also, auto indent the first line menu"
651 :active (eq yas/indent-line 'auto)
652 :style toggle :selected yas/also-auto-indent-first-line]
653 )
654 ("Prompting method"
655 ["System X-widget" (setq yas/prompt-functions
656 (cons 'yas/x-prompt
657 (remove 'yas/x-prompt
658 yas/prompt-functions)))
659 :help "Use your windowing system's (gtk, mac, windows, etc...) default menu"
660 :active t :style radio :selected (eq (car yas/prompt-functions)
661 'yas/x-prompt)]
662 ["Dropdown-list" (setq yas/prompt-functions
663 (cons 'yas/dropdown-prompt
664 (remove 'yas/dropdown-prompt
665 yas/prompt-functions)))
666 :help "Use a special dropdown list"
667 :active t :style radio :selected (eq (car yas/prompt-functions)
668 'yas/dropdown-prompt)]
669 ["Ido" (setq yas/prompt-functions
670 (cons 'yas/ido-prompt
671 (remove 'yas/ido-prompt
672 yas/prompt-functions)))
673 :help "Use an ido-style minibuffer prompt"
674 :active t :style radio :selected (eq (car yas/prompt-functions)
675 'yas/ido-prompt)]
676 ["Completing read" (setq yas/prompt-functions
677 (cons 'yas/completing-prompt
678 (remove 'yas/completing-prompt-prompt
679 yas/prompt-functions)))
680 :help "Use a normal minibuffer prompt"
681 :active t :style radio :selected (eq (car yas/prompt-functions)
682 'yas/completing-prompt-prompt)]
683 )
684 ("Misc"
685 ["Wrap region in exit marker"
686 (setq yas/wrap-around-region
687 (not yas/wrap-around-region))
688 :help "If non-nil automatically wrap the selected text in the $0 snippet exit"
689 :style toggle :selected yas/wrap-around-region]
690 ["Allow stacked expansions "
691 (setq yas/triggers-in-field
692 (not yas/triggers-in-field))
693 :help "If non-nil allow snippets to be triggered inside other snippet fields"
694 :style toggle :selected yas/triggers-in-field]
695 ["Revive snippets on undo "
696 (setq yas/snippet-revival
697 (not yas/snippet-revival))
698 :help "If non-nil allow snippets to become active again after undo"
699 :style toggle :selected yas/snippet-revival]
700 ["Good grace "
701 (setq yas/good-grace
702 (not yas/good-grace))
703 :help "If non-nil don't raise errors in bad embedded eslip in snippets"
704 :style toggle :selected yas/good-grace]
705 ["Ignore filenames as triggers"
706 (setq yas/ignore-filenames-as-triggers
707 (not yas/ignore-filenames-as-triggers))
708 :help "If non-nil don't derive tab triggers from filenames"
709 :style toggle :selected yas/ignore-filenames-as-triggers]
710 )
711 "----"
712 ["Load snippets..." yas/load-directory
713 :help "Load snippets from a specific directory"]
714 ["Reload everything" yas/reload-all
715 :help "Cleanup stuff, reload snippets, rebuild menus"]
716 ["About" yas/about
717 :help "Display some information about YASsnippet"]))
718 ;; Now for the stuff that has direct keybindings
719 ;;
720 (define-key map "\C-c&\C-s" 'yas/insert-snippet)
721 (define-key map "\C-c&\C-n" 'yas/new-snippet)
722 (define-key map "\C-c&\C-v" 'yas/visit-snippet-file)
723 (define-key map "\C-c&\C-f" 'yas/find-snippets)
724 map))
725
726 (defvar yas/minor-mode-map (yas/init-minor-keymap)
727 "The keymap used when `yas/minor-mode' is active.")
728
729 (defun yas/trigger-key-reload (&optional unbind-key)
730 "Rebind `yas/expand' to the new value of `yas/trigger-key'.
731
732 With optional UNBIND-KEY, try to unbind that key from
733 `yas/minor-mode-map'."
734 (when (and unbind-key
735 (stringp unbind-key)
736 (not (string= unbind-key "")))
737 (define-key yas/minor-mode-map (read-kbd-macro unbind-key) nil))
738 (when (and yas/trigger-key
739 (stringp yas/trigger-key)
740 (not (string= yas/trigger-key "")))
741 (define-key yas/minor-mode-map (read-kbd-macro yas/trigger-key) 'yas/expand)))
742
743 (defvar yas/tables (make-hash-table)
744 "A hash table of MAJOR-MODE symbols to `yas/table' objects.")
745
746 (defvar yas/direct-keymaps (list)
747 "Keymap alist supporting direct snippet keybindings.
748
749 This variable is is placed `emulation-mode-map-alists'.
750
751 Its elements looks like (TABLE-NAME . KEYMAP) and are
752 calculated when loading snippets. TABLE-NAME is a variable
753 set buffer-locally when entering `yas/minor-mode'. KEYMAP binds
754 all defined direct keybindings to the command
755 `yas/expand-from-keymap', which acts similarly to `yas/expand'")
756
757 (defun yas/direct-keymaps-reload ()
758 "Force reload the direct keybinding for active snippet tables."
759 (interactive)
760 (setq yas/direct-keymaps nil)
761 (maphash #'(lambda (name table)
762 (mapc #'(lambda (table)
763 (push (cons (intern (format "yas//direct-%s" name))
764 (yas/table-direct-keymap table))
765 yas/direct-keymaps))
766 (cons table (yas/table-get-all-parents table))))
767 yas/tables))
768
769 (defun yas/direct-keymaps-set-vars ()
770 (let ((modes-to-activate (list major-mode))
771 (mode major-mode))
772 (while (setq mode (get mode 'derived-mode-parent))
773 (push mode modes-to-activate))
774 (dolist (mode (yas/extra-modes))
775 (push mode modes-to-activate))
776 (dolist (mode modes-to-activate)
777 (let ((name (intern (format "yas//direct-%s" mode))))
778 (set-default name nil)
779 (set (make-local-variable name) t)))))
780
781 (defvar yas/minor-mode-hook nil
782 "Hook run when yas/minor-mode is turned on")
783
784 ;;;###autoload
785 (define-minor-mode yas/minor-mode
786 "Toggle YASnippet mode.
787
788 When YASnippet mode is enabled, the `tas/trigger-key' key expands
789 snippets of code depending on the mode.
790
791 With no argument, this command toggles the mode.
792 positive prefix argument turns on the mode.
793 Negative prefix argument turns off the mode.
794
795 You can customize the key through `yas/trigger-key'.
796
797 Key bindings:
798 \\{yas/minor-mode-map}"
799 nil
800 ;; The indicator for the mode line.
801 " yas"
802 :group 'yasnippet
803 (cond (yas/minor-mode
804 ;; Reload the trigger key
805 ;;
806 (yas/trigger-key-reload)
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 to
810 ;; index `yas/direct-keymaps'.
811 ;;
812 ;; Also install the post-command-hook.
813 ;;
814 (add-hook 'emulation-mode-map-alists 'yas/direct-keymaps)
815 (add-hook 'post-command-hook 'yas/post-command-handler nil t)
816 (add-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce 'append))
817 (t
818 ;; Uninstall the direct keymaps and the post-command hook
819 ;;
820 (remove-hook 'post-command-hook 'yas/post-command-handler t)
821 (remove-hook 'emulation-mode-map-alists 'yas/direct-keymaps))))
822
823 (defun yas/direct-keymaps-set-vars-runonce ()
824 (yas/direct-keymaps-set-vars)
825 (remove-hook 'yas/minor-mode-hook 'yas/direct-keymaps-set-vars-runonce))
826
827 (defvar yas/dont-activate nil
828 "If non-nil don't let `yas/minor-mode-on' active yas for this buffer.
829
830 `yas/minor-mode-on' is usually called by `yas/global-mode' so
831 this effectively lets you define exceptions to the \"global\"
832 behaviour.")
833 (make-variable-buffer-local 'yas/dont-activate)
834
835 (defun yas/minor-mode-on ()
836 "Turn on YASnippet minor mode.
837
838 Do this unless `yas/dont-activate' is t "
839 (interactive)
840 (unless (or (minibufferp)
841 (and (functionp yas/dont-activate)
842 (funcall yas/dont-activate))
843 (and (not (functionp yas/dont-activate))
844 yas/dont-activate))
845 ;; Load all snippets definitions unless we still don't have a
846 ;; root-directory or some snippets have already been loaded.
847 ;;
848 (unless (or (null yas/snippet-dirs)
849 (> (hash-table-count yas/tables) 0))
850 (yas/reload-all))
851 (yas/minor-mode 1)))
852
853 (defun yas/minor-mode-off ()
854 "Turn off YASnippet minor mode."
855 (interactive)
856 (yas/minor-mode -1))
857
858 (define-globalized-minor-mode yas/global-mode yas/minor-mode yas/minor-mode-on
859 :group 'yasnippet
860 :require 'yasnippet)
861
862 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
863 ;; Major mode stuff
864 ;;
865 (defvar yas/font-lock-keywords
866 (append '(("^#.*$" . font-lock-comment-face))
867 lisp-font-lock-keywords
868 lisp-font-lock-keywords-1
869 lisp-font-lock-keywords-2
870 '(("$\\([0-9]+\\)"
871 (0 font-lock-keyword-face)
872 (1 font-lock-string-face t))
873 ("${\\([0-9]+\\):?"
874 (0 font-lock-keyword-face)
875 (1 font-lock-warning-face t))
876 ("${" font-lock-keyword-face)
877 ("$[0-9]+?" font-lock-preprocessor-face)
878 ("\\(\\$(\\)" 1 font-lock-preprocessor-face)
879 ("}"
880 (0 font-lock-keyword-face)))))
881
882 (defun yas/init-major-keymap ()
883 (let ((map (make-sparse-keymap)))
884 (easy-menu-define nil
885 map
886 "Menu used when snippet-mode is active."
887 (cons "Snippet"
888 (mapcar #'(lambda (ent)
889 (when (third ent)
890 (define-key map (third ent) (second ent)))
891 (vector (first ent) (second ent) t))
892 (list
893 (list "Load this snippet" 'yas/load-snippet-buffer "\C-c\C-c")
894 (list "Try out this snippet" 'yas/tryout-snippet "\C-c\C-t")))))
895 map))
896
897 (defvar snippet-mode-map
898 (yas/init-major-keymap)
899 "The keymap used when `snippet-mode' is active")
900
901
902 (define-derived-mode snippet-mode text-mode "Snippet"
903 "A mode for editing yasnippets"
904 (set-syntax-table (standard-syntax-table))
905 (setq font-lock-defaults '(yas/font-lock-keywords))
906 (set (make-local-variable 'require-final-newline) nil)
907 (use-local-map snippet-mode-map))
908
909
910 \f
911 ;;; Internal structs for template management
912
913 (defstruct (yas/template (:constructor yas/make-blank-template))
914 "A template for a snippet."
915 table
916 key
917 content
918 name
919 condition
920 expand-env
921 file
922 keybinding
923 uuid
924 menu-binding-pair
925 group ;; as dictated by the #group: directive or .yas-make-groups
926 perm-group ;; as dictated by `yas/define-menu'
927 )
928
929 (defun yas/populate-template (template &rest args)
930 "Helper function to populate a template with properties"
931 (let (p v)
932 (while args
933 (aset template
934 (position (intern (substring (symbol-name (car args)) 1))
935 (mapcar #'car (get 'yas/template 'cl-struct-slots)))
936 (second args))
937 (setq args (cddr args)))
938 template))
939
940 (defstruct (yas/table (:constructor yas/make-snippet-table (name)))
941 "A table to store snippets for a particular mode.
942
943 Has the following fields:
944
945 `yas/table-name'
946
947 A symbol name normally corresponding to a major mode, but can
948 also be a pseudo major-mode to be referenced in
949 `yas/extra-modes', for example.
950
951 `yas/table-hash'
952
953 A hash table (KEY . NAMEHASH), known as the \"keyhash\". KEY is
954 a string or a vector, where the former is the snippet's trigger
955 and the latter means it's a direct keybinding. NAMEHASH is yet
956 another hash of (NAME . TEMPLATE) where NAME is the snippet's
957 name and TEMPLATE is a `yas/template' object.
958
959 `yas/table-parents'
960
961 A list of tables considered parents of this table: i.e. when
962 searching for expansions they are searched as well.
963
964 `yas/table-direct-keymap'
965
966 A keymap for the snippets in this table that have direct
967 keybindings. This is kept in sync with the keyhash, i.e., all
968 the elements of the keyhash that are vectors appear here as
969 bindings to `yas/expand-from-keymap'.
970
971 `yas/table-uuidhash'
972
973 A hash table mapping snippets uuid's to the same `yas/template'
974 objects. A snippet uuid defaults to the snippet's name.
975 "
976 name
977 (hash (make-hash-table :test 'equal))
978 (uuidhash (make-hash-table :test 'equal))
979 (parents nil)
980 (direct-keymap (make-sparse-keymap)))
981
982 (defun yas/get-template-by-uuid (mode uuid)
983 "Find the snippet template in MODE by its UUID."
984 (let* ((table (gethash mode yas/tables mode)))
985 (when table
986 (gethash uuid (yas/table-uuidhash table)))))
987
988 ;; Apropos storing/updating, this works with two steps:
989 ;;
990 ;; 1. `yas/remove-template-by-uuid' to remove any existing mappings by
991 ;; snippet uuid
992 ;;
993 ;; 2. `yas/add-template' to add the mappings again:
994 ;;
995 ;; Create or index the entry in TABLES's `yas/table-hash'
996 ;; linking KEY to a namehash. That namehash links NAME to
997 ;; TEMPLATE, and is also created a new namehash inside that
998 ;; entry.
999 ;;
1000 (defun yas/remove-template-by-uuid (table uuid)
1001 "Remove from TABLE a template identified by UUID."
1002 (let ((template (gethash uuid (yas/table-uuidhash table))))
1003 (when template
1004 (let* ((name (yas/template-name template))
1005 (empty-keys nil))
1006 ;; Remove the name from each of the targeted namehashes
1007 ;;
1008 (maphash #'(lambda (k v)
1009 (let ((template (gethash name v)))
1010 (when (and template
1011 (eq uuid (yas/template-uuid template)))
1012 (remhash name v)
1013 (when (zerop (hash-table-count v))
1014 (push k empty-keys)))))
1015 (yas/table-hash table))
1016 ;; Remove the namehashed themselves if they've become empty
1017 ;;
1018 (dolist (key empty-keys)
1019 (remhash key (yas/table-hash table)))
1020
1021 ;; Finally, remove the uuid from the uuidhash
1022 ;;
1023 (remhash uuid (yas/table-uuidhash table))))))
1024
1025
1026 (defun yas/add-template (table template)
1027 "Store in TABLE the snippet template TEMPLATE.
1028
1029 KEY can be a string (trigger key) of a vector (direct
1030 keybinding)."
1031 (let ((name (yas/template-name template))
1032 (key (yas/template-key template))
1033 (keybinding (yas/template-keybinding template))
1034 (menu-binding (car (yas/template-menu-binding-pair template))))
1035 (dolist (k (remove nil (list key keybinding)))
1036 (puthash name
1037 template
1038 (or (gethash k
1039 (yas/table-hash table))
1040 (puthash k
1041 (make-hash-table :test 'equal)
1042 (yas/table-hash table))))
1043 (when (vectorp k)
1044 (define-key (yas/table-direct-keymap table) k 'yas/expand-from-keymap)))
1045
1046 (when menu-binding
1047 (setf (getf (cdr menu-binding) :keys)
1048 (or (and keybinding (key-description keybinding))
1049 (and key (concat key yas/trigger-symbol))))
1050 (setcar (cdr menu-binding)
1051 name))
1052
1053 (puthash (yas/template-uuid template) template (yas/table-uuidhash table))))
1054
1055 (defun yas/update-template (snippet-table template)
1056 "Add or update TEMPLATE in SNIPPET-TABLE.
1057
1058 Also takes care of adding and updaring to the associated menu."
1059 ;; Remove from table by uuid
1060 ;;
1061 (yas/remove-template-by-uuid snippet-table (yas/template-uuid template))
1062 ;; Add to table again
1063 ;;
1064 (yas/add-template snippet-table template)
1065 ;; Take care of the menu
1066 ;;
1067 (let ((keymap (yas/menu-keymap-get-create snippet-table))
1068 (group (yas/template-group template)))
1069 (when (and yas/use-menu
1070 keymap
1071 (not (cdr (yas/template-menu-binding-pair template))))
1072 ;; Remove from menu keymap
1073 ;;
1074 (yas/delete-from-keymap keymap (yas/template-uuid template))
1075
1076 ;; Add necessary subgroups as necessary.
1077 ;;
1078 (dolist (subgroup group)
1079 (let ((subgroup-keymap (lookup-key keymap (vector (make-symbol subgroup)))))
1080 (unless (and subgroup-keymap
1081 (keymapp subgroup-keymap))
1082 (setq subgroup-keymap (make-sparse-keymap))
1083 (define-key keymap (vector (make-symbol subgroup))
1084 `(menu-item ,subgroup ,subgroup-keymap)))
1085 (setq keymap subgroup-keymap)))
1086
1087 ;; Add this entry to the keymap
1088 ;;
1089 (let ((menu-binding-pair (yas/snippet-menu-binding-pair-get-create template)))
1090 (define-key keymap (vector (make-symbol (yas/template-uuid template))) (car menu-binding-pair))))))
1091
1092 (defun yas/fetch (table key)
1093 "Fetch templates in TABLE by KEY.
1094
1095 Return a list of cons (NAME . TEMPLATE) where NAME is a
1096 string and TEMPLATE is a `yas/template' structure."
1097 (let* ((keyhash (yas/table-hash table))
1098 (namehash (and keyhash (gethash key keyhash))))
1099 (when namehash
1100 (yas/filter-templates-by-condition
1101 (let (alist)
1102 (maphash #'(lambda (k v)
1103 (push (cons k v) alist))
1104 namehash)
1105 alist)))))
1106
1107 \f
1108 ;;; Filtering/condition logic
1109
1110 (defun yas/eval-condition (condition)
1111 (condition-case err
1112 (save-excursion
1113 (save-restriction
1114 (save-match-data
1115 (eval condition))))
1116 (error (progn
1117 (message (format "[yas] error in condition evaluation: %s"
1118 (error-message-string err)))
1119 nil))))
1120
1121
1122 (defun yas/filter-templates-by-condition (templates)
1123 "Filter the templates using the applicable condition.
1124
1125 TEMPLATES is a list of cons (NAME . TEMPLATE) where NAME is a
1126 string and TEMPLATE is a `yas/template' structure.
1127
1128 This function implements the rules described in
1129 `yas/buffer-local-condition'. See that variables documentation."
1130 (let ((requirement (yas/require-template-specific-condition-p)))
1131 (if (eq requirement 'always)
1132 templates
1133 (remove-if-not #'(lambda (pair)
1134 (yas/template-can-expand-p
1135 (yas/template-condition (cdr pair)) requirement))
1136 templates))))
1137
1138 (defun yas/require-template-specific-condition-p ()
1139 "Decides if this buffer requests/requires snippet-specific
1140 conditions to filter out potential expansions."
1141 (if (eq 'always yas/buffer-local-condition)
1142 'always
1143 (let ((local-condition (or (and (consp yas/buffer-local-condition)
1144 (yas/eval-condition yas/buffer-local-condition))
1145 yas/buffer-local-condition)))
1146 (when local-condition
1147 (if (eq local-condition t)
1148 t
1149 (and (consp local-condition)
1150 (eq 'require-snippet-condition (car local-condition))
1151 (symbolp (cdr local-condition))
1152 (cdr local-condition)))))))
1153
1154 (defun yas/template-can-expand-p (condition requirement)
1155 "Evaluates CONDITION and REQUIREMENT and returns a boolean"
1156 (let* ((result (or (null condition)
1157 (yas/eval-condition condition))))
1158 (cond ((eq requirement t)
1159 result)
1160 (t
1161 (eq requirement result)))))
1162
1163 (defun yas/table-get-all-parents (table)
1164 "Returns a list of all parent tables of TABLE"
1165 (let ((parents (yas/table-parents table)))
1166 (when parents
1167 (append (copy-list parents)
1168 (mapcan #'yas/table-get-all-parents parents)))))
1169
1170 (defun yas/table-templates (table)
1171 (when table
1172 (let ((acc (list)))
1173 (maphash #'(lambda (key namehash)
1174 (maphash #'(lambda (name template)
1175 (push (cons name template) acc))
1176 namehash))
1177 (yas/table-hash table))
1178 (yas/filter-templates-by-condition acc))))
1179
1180 (defun yas/current-key ()
1181 "Get the key under current position. A key is used to find
1182 the template of a snippet in the current snippet-table."
1183 (let ((start (point))
1184 (end (point))
1185 (syntaxes yas/key-syntaxes)
1186 syntax
1187 done
1188 templates)
1189 (while (and (not done) syntaxes)
1190 (setq syntax (car syntaxes))
1191 (setq syntaxes (cdr syntaxes))
1192 (save-excursion
1193 (skip-syntax-backward syntax)
1194 (setq start (point)))
1195 (setq templates
1196 (mapcan #'(lambda (table)
1197 (yas/fetch table (buffer-substring-no-properties start end)))
1198 (yas/get-snippet-tables)))
1199 (if templates
1200 (setq done t)
1201 (setq start end)))
1202 (list templates
1203 start
1204 end)))
1205
1206
1207 (defun yas/table-all-keys (table)
1208 (when table
1209 (let ((acc))
1210 (maphash #'(lambda (key templates)
1211 (when (yas/filter-templates-by-condition templates)
1212 (push key acc)))
1213 (yas/table-hash table))
1214 acc)))
1215
1216 \f
1217 ;;; Internal functions
1218
1219 (defun yas/real-mode? (mode)
1220 "Try to find out if MODE is a real mode. The MODE bound to
1221 a function (like `c-mode') is considered real mode. Other well
1222 known mode like `ruby-mode' which is not part of Emacs might
1223 not bound to a function until it is loaded. So yasnippet keeps
1224 a list of modes like this to help the judgement."
1225 (or (fboundp mode)
1226 (find mode yas/known-modes)))
1227
1228 (defun yas/eval-lisp (form)
1229 "Evaluate FORM and convert the result to string."
1230 (let ((retval (catch 'yas/exception
1231 (condition-case err
1232 (save-excursion
1233 (save-restriction
1234 (save-match-data
1235 (widen)
1236 (let ((result (eval form)))
1237 (when result
1238 (format "%s" result))))))
1239 (error (if yas/good-grace
1240 (format "[yas] elisp error! %s" (error-message-string err))
1241 (error (format "[yas] elisp error: %s"
1242 (error-message-string err)))))))))
1243 (when (and (consp retval)
1244 (eq 'yas/exception (car retval)))
1245 (error (cdr retval)))
1246 retval))
1247
1248 (defun yas/eval-lisp-no-saves (form)
1249 (condition-case err
1250 (eval form)
1251 (error (if yas/good-grace
1252 (format "[yas] elisp error! %s" (error-message-string err))
1253 (error (format "[yas] elisp error: %s"
1254 (error-message-string err)))))))
1255
1256 (defun yas/read-lisp (string &optional nil-on-error)
1257 "Read STRING as a elisp expression and return it.
1258
1259 In case STRING in an invalid expression and NIL-ON-ERROR is nil,
1260 return an expression that when evaluated will issue an error."
1261 (condition-case err
1262 (read string)
1263 (error (and (not nil-on-error)
1264 `(error (error-message-string err))))))
1265
1266 (defun yas/read-keybinding (keybinding)
1267 "Read KEYBINDING as a snippet keybinding, return a vector."
1268 (when (and keybinding
1269 (not (string-match "keybinding" keybinding)))
1270 (condition-case err
1271 (let ((res (or (and (string-match "^\\[.*\\]$" keybinding)
1272 (read keybinding))
1273 (read-kbd-macro keybinding 'need-vector))))
1274 res)
1275 (error
1276 (message "[yas] warning: keybinding \"%s\" invalid since %s."
1277 keybinding (error-message-string err))
1278 nil))))
1279
1280 (defvar yas/extra-modes nil
1281 "If non-nil, also lookup snippets for this/these modes.
1282
1283 Can be a symbol or a list of symbols.
1284
1285 This variable probably makes more sense as buffer-local, so
1286 ensure your use `make-local-variable' when you set it.")
1287 (defun yas/extra-modes ()
1288 (if (listp yas/extra-modes) yas/extra-modes (list yas/extra-modes)))
1289 (defvaralias 'yas/mode-symbol 'yas/extra-modes)
1290
1291 (defun yas/table-get-create (mode)
1292 "Get the snippet table corresponding to MODE.
1293
1294 Optional DIRECTORY gets recorded as the default directory to
1295 search for snippet files if the retrieved/created table didn't
1296 already have such a property."
1297 (let ((table (gethash mode
1298 yas/tables)))
1299 (unless table
1300 (setq table (yas/make-snippet-table (symbol-name mode)))
1301 (puthash mode table yas/tables)
1302 (aput 'yas/direct-keymaps (intern (format "yas//direct-%s" mode))
1303 (yas/table-direct-keymap table)))
1304 table))
1305
1306 (defun yas/get-snippet-tables (&optional mode-symbol dont-search-parents)
1307 "Get snippet tables for current buffer.
1308
1309 Return a list of 'yas/table' objects indexed by mode.
1310
1311 The modes are tried in this order: optional MODE-SYMBOL, then
1312 `yas/extra-modes', then `major-mode' then, unless
1313 DONT-SEARCH-PARENTS is non-nil, the guessed parent mode of either
1314 MODE-SYMBOL or `major-mode'.
1315
1316 Guessing is done by looking up the MODE-SYMBOL's
1317 `derived-mode-parent' property, see also `derived-mode-p'."
1318 (let ((mode-tables
1319 (remove nil
1320 (mapcar #'(lambda (mode)
1321 (gethash mode yas/tables))
1322 (remove nil (append (list mode-symbol)
1323 (yas/extra-modes)
1324 (list major-mode
1325 (and (not dont-search-parents)
1326 (get major-mode
1327 'derived-mode-parent)))))))))
1328 (remove-duplicates
1329 (append mode-tables
1330 (mapcan #'yas/table-get-all-parents mode-tables)))))
1331
1332 (defun yas/menu-keymap-get-create (table)
1333 "Get or create the main menu keymap correspondong to MODE.
1334
1335 This may very well create a plethora of menu keymaps and arrange
1336 them in all `yas/menu-table'"
1337 (let* ((mode (intern (yas/table-name table)))
1338 (menu-keymap (or (gethash mode yas/menu-table)
1339 (puthash mode (make-sparse-keymap) yas/menu-table)))
1340 (parents (yas/table-parents table)))
1341 (mapc #'yas/menu-keymap-get-create parents)
1342 (define-key yas/minor-mode-menu (vector mode)
1343 `(menu-item ,(symbol-name mode) ,menu-keymap
1344 :visible (yas/show-menu-p ',mode)))
1345 menu-keymap))
1346
1347 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1348 ;;; Template-related and snippet loading functions
1349
1350 (defun yas/parse-template (&optional file)
1351 "Parse the template in the current buffer.
1352
1353 Optional FILE is the absolute file name of the file being
1354 parsed.
1355
1356 Optional GROUP is the group where the template is to go,
1357 otherwise we attempt to calculate it from FILE.
1358
1359 Return a snippet-definition, i.e. a list
1360
1361 (KEY TEMPLATE NAME CONDITION GROUP VARS FILE KEYBINDING UUID)
1362
1363 If the buffer contains a line of \"# --\" then the contents above
1364 this line are ignored. Directives can set most of these with the syntax:
1365
1366 # directive-name : directive-value
1367
1368 Here's a list of currently recognized directives:
1369
1370 * type
1371 * name
1372 * contributor
1373 * condition
1374 * group
1375 * key
1376 * expand-env
1377 * binding
1378 * uuid"
1379 (goto-char (point-min))
1380 (let* ((type 'snippet)
1381 (name (and file
1382 (file-name-nondirectory file)))
1383 (key (unless yas/ignore-filenames-as-triggers
1384 (and name
1385 (file-name-sans-extension name))))
1386 template
1387 bound
1388 condition
1389 (group (and file
1390 (yas/calculate-group file)))
1391 expand-env
1392 binding
1393 uuid)
1394 (if (re-search-forward "^# --\n" nil t)
1395 (progn (setq template
1396 (buffer-substring-no-properties (point)
1397 (point-max)))
1398 (setq bound (point))
1399 (goto-char (point-min))
1400 (while (re-search-forward "^# *\\([^ ]+?\\) *: *\\(.*\\)$" bound t)
1401 (when (string= "uuid" (match-string-no-properties 1))
1402 (setq uuid (match-string-no-properties 2)))
1403 (when (string= "type" (match-string-no-properties 1))
1404 (setq type (if (string= "command" (match-string-no-properties 2))
1405 'command
1406 'snippet)))
1407 (when (string= "key" (match-string-no-properties 1))
1408 (setq key (match-string-no-properties 2)))
1409 (when (string= "name" (match-string-no-properties 1))
1410 (setq name (match-string-no-properties 2)))
1411 (when (string= "condition" (match-string-no-properties 1))
1412 (setq condition (yas/read-lisp (match-string-no-properties 2))))
1413 (when (string= "group" (match-string-no-properties 1))
1414 (setq group (match-string-no-properties 2)))
1415 (when (string= "expand-env" (match-string-no-properties 1))
1416 (setq expand-env (yas/read-lisp (match-string-no-properties 2)
1417 'nil-on-error)))
1418 (when (string= "binding" (match-string-no-properties 1))
1419 (setq binding (match-string-no-properties 2)))))
1420 (setq template
1421 (buffer-substring-no-properties (point-min) (point-max))))
1422 (when (eq type 'command)
1423 (setq template (yas/read-lisp (concat "(progn" template ")"))))
1424 (when group
1425 (setq group (split-string group "\\.")))
1426 (list key template name condition group expand-env file binding uuid)))
1427
1428 (defun yas/calculate-group (file)
1429 "Calculate the group for snippet file path FILE."
1430 (let* ((dominating-dir (locate-dominating-file file
1431 ".yas-make-groups"))
1432 (extra-path (and dominating-dir
1433 (replace-regexp-in-string (concat "^"
1434 (expand-file-name dominating-dir))
1435 ""
1436 (expand-file-name file))))
1437 (extra-dir (and extra-path
1438 (file-name-directory extra-path)))
1439 (group (and extra-dir
1440 (replace-regexp-in-string "/"
1441 "."
1442 (directory-file-name extra-dir)))))
1443 group))
1444
1445 (defun yas/subdirs (directory &optional file?)
1446 "Return subdirs or files of DIRECTORY according to FILE?."
1447 (remove-if (lambda (file)
1448 (or (string-match "^\\."
1449 (file-name-nondirectory file))
1450 (string-match "^#.*#$"
1451 (file-name-nondirectory file))
1452 (string-match "~$"
1453 (file-name-nondirectory file))
1454 (if file?
1455 (file-directory-p file)
1456 (not (file-directory-p file)))))
1457 (directory-files directory t)))
1458
1459 (defun yas/make-menu-binding (template)
1460 (let ((mode (intern (yas/table-name (yas/template-table template)))))
1461 `(lambda () (interactive) (yas/expand-or-visit-from-menu ',mode ,(yas/template-uuid template)))))
1462
1463 (defun yas/expand-or-visit-from-menu (mode uuid)
1464 (let* ((table (yas/table-get-create mode))
1465 (yas/current-template (and table
1466 (gethash uuid (yas/table-uuidhash table)))))
1467 (when yas/current-template
1468 (if yas/visit-from-menu
1469 (yas/visit-snippet-file-1 yas/current-template)
1470 (let ((where (if (region-active-p)
1471 (cons (region-beginning) (region-end))
1472 (cons (point) (point)))))
1473 (yas/expand-snippet (yas/template-content yas/current-template)
1474 (car where)
1475 (cdr where)))))))
1476
1477 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1478 ;; Popping up for keys and templates
1479 ;;
1480 (defun yas/prompt-for-template (templates &optional prompt)
1481 "Interactively choose a template from the list TEMPLATES.
1482
1483 TEMPLATES is a list of `yas/template'."
1484 (when templates
1485 (setq templates
1486 (sort templates #'(lambda (t1 t2)
1487 (< (length (yas/template-name t1))
1488 (length (yas/template-name t2))))))
1489 (if yas/x-pretty-prompt-templates
1490 (yas/x-pretty-prompt-templates "Choose a snippet" templates)
1491 (some #'(lambda (fn)
1492 (funcall fn (or prompt "Choose a snippet: ")
1493 templates
1494 #'yas/template-name))
1495 yas/prompt-functions))))
1496
1497 (defun yas/prompt-for-keys (keys &optional prompt)
1498 "Interactively choose a template key from the list KEYS."
1499 (when keys
1500 (some #'(lambda (fn)
1501 (funcall fn (or prompt "Choose a snippet key: ") keys))
1502 yas/prompt-functions)))
1503
1504 (defun yas/prompt-for-table (tables &optional prompt)
1505 (when tables
1506 (some #'(lambda (fn)
1507 (funcall fn (or prompt "Choose a snippet table: ")
1508 tables
1509 #'yas/table-name))
1510 yas/prompt-functions)))
1511
1512 (defun yas/x-prompt (prompt choices &optional display-fn)
1513 "Display choices in a x-window prompt."
1514 ;; FIXME: HACK: if we notice that one of the objects in choices is
1515 ;; actually a `yas/template', defer to `yas/x-prompt-pretty-templates'
1516 ;;
1517 ;; This would be better implemented by passing CHOICES as a
1518 ;; strucutred tree rather than a list. Modifications would go as far
1519 ;; up as `yas/all-templates' I think.
1520 ;;
1521 (when (and window-system choices)
1522 (let ((chosen
1523 (let (menu d) ;; d for display
1524 (dolist (c choices)
1525 (setq d (or (and display-fn (funcall display-fn c))
1526 c))
1527 (cond ((stringp d)
1528 (push (cons (concat " " d) c) menu))
1529 ((listp d)
1530 (push (car d) menu))))
1531 (setq menu (list prompt (push "title" menu)))
1532 (x-popup-menu (if (fboundp 'posn-at-point)
1533 (let ((x-y (posn-x-y (posn-at-point (point)))))
1534 (list (list (+ (car x-y) 10)
1535 (+ (cdr x-y) 20))
1536 (selected-window)))
1537 t)
1538 menu))))
1539 (or chosen
1540 (keyboard-quit)))))
1541
1542 (defvar yas/x-pretty-prompt-templates nil
1543 "If non-nil, attempt to prompt for templates like TextMate.")
1544 (defun yas/x-pretty-prompt-templates (prompt templates)
1545 "Display TEMPLATES, grouping neatly by table name."
1546 (let ((pretty-alist (list))
1547 menu
1548 more-than-one-table
1549 prefix)
1550 (dolist (tl templates)
1551 (aput 'pretty-alist (yas/template-table tl) (cons tl (aget pretty-alist (yas/template-table tl)))))
1552 (setq more-than-one-table (> (length pretty-alist) 1))
1553 (setq prefix (if more-than-one-table
1554 " " ""))
1555 (dolist (table-and-templates pretty-alist)
1556 (when (cdr table-and-templates)
1557 (if more-than-one-table
1558 (push (yas/table-name (car table-and-templates)) menu))
1559 (dolist (template (cdr table-and-templates))
1560 (push (cons (concat prefix (yas/template-name template))
1561 template) menu))))
1562 (setq menu (nreverse menu))
1563 (or (x-popup-menu (if (fboundp 'posn-at-point)
1564 (let ((x-y (posn-x-y (posn-at-point (point)))))
1565 (list (list (+ (car x-y) 10)
1566 (+ (cdr x-y) 20))
1567 (selected-window)))
1568 t)
1569 (list prompt (push "title" menu)))
1570 (keyboard-quit))))
1571
1572 (defun yas/ido-prompt (prompt choices &optional display-fn)
1573 (when (and (featurep 'ido)
1574 ido-mode)
1575 (yas/completing-prompt prompt choices display-fn #'ido-completing-read)))
1576
1577 (eval-when-compile (require 'dropdown-list nil t))
1578 (defun yas/dropdown-prompt (prompt choices &optional display-fn)
1579 (when (featurep 'dropdown-list)
1580 (let (formatted-choices
1581 filtered-choices
1582 d
1583 n)
1584 (dolist (choice choices)
1585 (setq d (or (and display-fn (funcall display-fn choice))
1586 choice))
1587 (when (stringp d)
1588 (push d formatted-choices)
1589 (push choice filtered-choices)))
1590
1591 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1592 (if n
1593 (nth n filtered-choices)
1594 (keyboard-quit)))))
1595
1596 (defun yas/completing-prompt (prompt choices &optional display-fn completion-fn)
1597 (let (formatted-choices
1598 filtered-choices
1599 chosen
1600 d
1601 (completion-fn (or completion-fn
1602 #'completing-read)))
1603 (dolist (choice choices)
1604 (setq d (or (and display-fn (funcall display-fn choice))
1605 choice))
1606 (when (stringp d)
1607 (push d formatted-choices)
1608 (push choice filtered-choices)))
1609 (setq chosen (and formatted-choices
1610 (funcall completion-fn prompt
1611 formatted-choices
1612 nil
1613 'require-match
1614 nil
1615 nil)))
1616 (when chosen
1617 (nth (position chosen formatted-choices :test #'string=) filtered-choices))))
1618
1619 (defun yas/no-prompt (prompt choices &optional display-fn)
1620 (first choices))
1621
1622 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1623 ;; Loading snippets from files
1624 ;;
1625 (defun yas/load-directory-1 (directory &optional mode-sym parents)
1626 "Recursively load snippet templates from DIRECTORY."
1627
1628 ;; Load .yas-setup.el files wherever we find them
1629 ;;
1630 (let ((file (concat directory "/" ".yas-setup")))
1631 (when (or (file-readable-p (concat file ".el"))
1632 (file-readable-p (concat file ".elc")))
1633 (load file)))
1634
1635 ;;
1636 ;;
1637 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1638 (let* ((major-mode-and-parents (if mode-sym
1639 (cons mode-sym parents)
1640 (yas/compute-major-mode-and-parents (concat directory
1641 "/dummy"))))
1642 (yas/ignore-filenames-as-triggers
1643 (or yas/ignore-filenames-as-triggers
1644 (file-exists-p (concat directory "/"
1645 ".yas-ignore-filenames-as-triggers"))))
1646 (snippet-defs nil))
1647 ;; load the snippet files
1648 ;;
1649 (with-temp-buffer
1650 (dolist (file (yas/subdirs directory 'no-subdirs-just-files))
1651 (when (file-readable-p file)
1652 (insert-file-contents file nil nil nil t)
1653 (push (yas/parse-template file)
1654 snippet-defs))))
1655 (when snippet-defs
1656 (yas/define-snippets (car major-mode-and-parents)
1657 snippet-defs
1658 (cdr major-mode-and-parents)))
1659 ;; now recurse to a lower level
1660 ;;
1661 (dolist (subdir (yas/subdirs directory))
1662 (yas/load-directory-1 subdir
1663 (car major-mode-and-parents)
1664 (cdr major-mode-and-parents))))))
1665
1666 (defun yas/load-directory (directory)
1667 "Load snippet definition from a directory hierarchy.
1668
1669 Below the top-level directory, each directory is a mode
1670 name. And under each subdirectory, each file is a definition
1671 of a snippet. The file name is the trigger key and the
1672 content of the file is the template."
1673 (interactive "DSelect the root directory: ")
1674 (unless (file-directory-p directory)
1675 (error "Error %s not a directory" directory))
1676 (unless yas/snippet-dirs
1677 (setq yas/snippet-dirs directory))
1678 (dolist (dir (yas/subdirs directory))
1679 (yas/load-directory-1 dir))
1680 (when (interactive-p)
1681 (message "[yas] Loaded snippets from %s." directory)))
1682
1683 (defun yas/load-snippet-dirs ()
1684 "Reload the directories listed in `yas/snippet-dirs' or
1685 prompt the user to select one."
1686 (if yas/snippet-dirs
1687 (dolist (directory (reverse (yas/snippet-dirs)))
1688 (yas/load-directory directory))
1689 (call-interactively 'yas/load-directory)))
1690
1691 (defun yas/reload-all (&optional reset-root-directory)
1692 "Reload all snippets and rebuild the YASnippet menu. "
1693 (interactive "P")
1694 ;; Turn off global modes and minor modes, save their state though
1695 ;;
1696 (let ((restore-global-mode (prog1 yas/global-mode
1697 (yas/global-mode -1)))
1698 (restore-minor-mode (prog1 yas/minor-mode
1699 (yas/minor-mode -1))))
1700 ;; Empty all snippet tables and all menu tables
1701 ;;
1702 (setq yas/tables (make-hash-table))
1703 (setq yas/menu-table (make-hash-table))
1704
1705 ;; Init the `yas/minor-mode-map', taking care not to break the
1706 ;; menu....
1707 ;;
1708 (setf (cdr yas/minor-mode-map)
1709 (cdr (yas/init-minor-keymap)))
1710
1711 (when reset-root-directory
1712 (setq yas/snippet-dirs nil))
1713
1714 ;; Reload the directories listed in `yas/snippet-dirs' or prompt
1715 ;; the user to select one.
1716 ;;
1717 (yas/load-snippet-dirs)
1718 ;; Reload the direct keybindings
1719 ;;
1720 (yas/direct-keymaps-reload)
1721 ;; Restore the mode configuration
1722 ;;
1723 (when restore-minor-mode
1724 (yas/minor-mode 1))
1725 (when restore-global-mode
1726 (yas/global-mode 1))
1727
1728 (message "[yas] Reloading everything... Done.")))
1729
1730 (defun yas/quote-string (string)
1731 "Escape and quote STRING.
1732 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1733 (concat "\""
1734 (replace-regexp-in-string "[\\\"]"
1735 "\\\\\\&"
1736 string
1737 t)
1738 "\""))
1739 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1740 ;;; Yasnippet Bundle
1741
1742 (defun yas/initialize ()
1743 "For backward compatibility, enable `yas/minor-mode' globally"
1744 (yas/global-mode 1))
1745
1746 (defun yas/compile-bundle
1747 (&optional yasnippet yasnippet-bundle snippet-roots code dropdown)
1748 "Compile snippets in SNIPPET-ROOTS to a single bundle file.
1749
1750 YASNIPPET is the yasnippet.el file path.
1751
1752 YASNIPPET-BUNDLE is the output file of the compile result.
1753
1754 SNIPPET-ROOTS is a list of root directories that contains the
1755 snippets definition.
1756
1757 CODE is the code to be placed at the end of the generated file
1758 and that can initialize the YASnippet bundle.
1759
1760 Last optional argument DROPDOWN is the filename of the
1761 dropdown-list.el library.
1762
1763 Here's the default value for all the parameters:
1764
1765 (yas/compile-bundle \"yasnippet.el\"
1766 \"yasnippet-bundle.el\"
1767 \"snippets\")
1768 \"(yas/initialize-bundle)
1769 ### autoload
1770 (require 'yasnippet-bundle)`\"
1771 \"dropdown-list.el\")
1772 "
1773 (interactive (concat "ffind the yasnippet.el file: \nFTarget bundle file: "
1774 "\nDSnippet directory to bundle: \nMExtra code? \nfdropdown-library: "))
1775
1776 (let* ((yasnippet (or yasnippet
1777 "yasnippet.el"))
1778 (yasnippet-bundle (or yasnippet-bundle
1779 "./yasnippet-bundle.el"))
1780 (snippet-roots (or snippet-roots
1781 "snippets"))
1782 (dropdown (or dropdown
1783 "dropdown-list.el"))
1784 (code (or (and code
1785 (condition-case err (read code) (error nil))
1786 code)
1787 (concat "(yas/initialize-bundle)"
1788 "\n;;;###autoload" ; break through so that won't
1789 "(require 'yasnippet-bundle)")))
1790 (dirs (or (and (listp snippet-roots) snippet-roots)
1791 (list snippet-roots)))
1792 (bundle-buffer nil))
1793 (with-temp-file yasnippet-bundle
1794 (insert ";;; yasnippet-bundle.el --- "
1795 "Yet another snippet extension (Auto compiled bundle)\n")
1796 (insert-file-contents yasnippet)
1797 (goto-char (point-max))
1798 (insert "\n")
1799 (when dropdown
1800 (insert-file-contents dropdown))
1801 (goto-char (point-max))
1802 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1803 (insert ";;;; Auto-generated code ;;;;\n")
1804 (insert ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n")
1805 (insert "(defun yas/initialize-bundle ()\n"
1806 " \"Initialize YASnippet and load snippets in the bundle.\"")
1807 (flet ((yas/define-snippets
1808 (mode snippets &optional parent-or-parents)
1809 (insert ";;; snippets for " (symbol-name mode) "\n")
1810 (let ((literal-snippets (list)))
1811 (dolist (snippet snippets)
1812 (let ((key (first snippet))
1813 (template-content (second snippet))
1814 (name (third snippet))
1815 (condition (fourth snippet))
1816 (group (fifth snippet))
1817 (expand-env (sixth snippet))
1818 (file nil) ;; (seventh snippet)) ;; omit on purpose
1819 (binding (eighth snippet))
1820 (uuid (ninth snippet)))
1821 (push `(,key
1822 ,template-content
1823 ,name
1824 ,condition
1825 ,group
1826 ,expand-env
1827 ,file
1828 ,binding
1829 ,uuid)
1830 literal-snippets)))
1831 (insert (pp-to-string `(yas/define-snippets ',mode ',literal-snippets ',parent-or-parents)))
1832 (insert "\n\n"))))
1833 (dolist (dir dirs)
1834 (dolist (subdir (yas/subdirs dir))
1835 (let ((file (concat subdir "/.yas-setup.el")))
1836 (when (file-readable-p file)
1837 (insert ";; Supporting elisp for subdir " (file-name-nondirectory subdir) "\n\n")
1838 (goto-char (+ (point)
1839 (second (insert-file-contents file))))))
1840 (yas/load-directory-1 subdir nil))))
1841
1842 (insert (pp-to-string `(yas/global-mode 1)))
1843 (insert ")\n\n" code "\n")
1844
1845 ;; bundle-specific provide and value for yas/dont-activate
1846 (let ((bundle-feature-name (file-name-nondirectory
1847 (file-name-sans-extension
1848 yasnippet-bundle))))
1849 (insert (pp-to-string `(set-default 'yas/dont-activate
1850 #'(lambda ()
1851 (and (or yas/snippet-dirs
1852 (featurep ',(make-symbol bundle-feature-name)))
1853 (null (yas/get-snippet-tables)))))))
1854 (insert (pp-to-string `(provide ',(make-symbol bundle-feature-name)))))
1855
1856 (insert ";;; "
1857 (file-name-nondirectory yasnippet-bundle)
1858 " ends here\n"))))
1859
1860 (defun yas/compile-textmate-bundle ()
1861 (interactive)
1862 (yas/compile-bundle "yasnippet.el"
1863 "./yasnippet-textmate-bundle.el"
1864 "extras/imported/"
1865 (concat "(yas/initialize-bundle)"
1866 "\n;;;###autoload" ; break through so that won't
1867 "(require 'yasnippet-textmate-bundle)")
1868 "dropdown-list.el"))
1869
1870 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1871 ;;; Some user level functions
1872 ;;;
1873
1874 (defun yas/about ()
1875 (interactive)
1876 (message (concat "yasnippet (version "
1877 yas/version
1878 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
1879
1880 (defun yas/define-snippets (mode snippets &optional parent-mode)
1881 "Define SNIPPETS for MODE.
1882
1883 SNIPPETS is a list of snippet definitions, each taking the
1884 following form
1885
1886 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1887
1888 Within these, only KEY and TEMPLATE are actually mandatory.
1889
1890 TEMPLATE might be a lisp form or a string, depending on whether
1891 this is a snippet or a snippet-command.
1892
1893 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1894 been `yas/read-lisp'-ed and will eventually be
1895 `yas/eval-lisp'-ed.
1896
1897 The remaining elements are strings.
1898
1899 FILE is probably of very little use if you're programatically
1900 defining snippets.
1901
1902 UUID is the snippets \"unique-id\". Loading a second snippet file
1903 with the same uuid replaced the previous snippet.
1904
1905 You can use `yas/parse-template' to return such lists based on
1906 the current buffers contents.
1907
1908 Optional PARENT-MODE can be used to specify the parent tables of
1909 MODE. It can be a mode symbol of a list of mode symbols. It does
1910 not need to be a real mode."
1911 ;; X) `snippet-table' is created or retrieved for MODE, same goes
1912 ;; for the list of snippet tables `parent-tables'.
1913 ;;
1914 (let ((snippet-table (yas/table-get-create mode))
1915 (parent-tables (mapcar #'yas/table-get-create
1916 (if (listp parent-mode)
1917 parent-mode
1918 (list parent-mode))))
1919 (template nil))
1920 ;; X) Connect `snippet-table' with `parent-tables'.
1921 ;;
1922 ;; TODO: this should be a remove-duplicates of the concatenation
1923 ;; of `snippet-table's existings parents with the new parents...
1924 ;;
1925 (dolist (parent parent-tables)
1926 (unless (find parent (yas/table-parents snippet-table))
1927 (push parent
1928 (yas/table-parents snippet-table))))
1929
1930 ;; X) Now, iterate for evey snippet def list
1931 ;;
1932 (dolist (snippet snippets)
1933 (setq template (yas/define-snippets-1 snippet
1934 snippet-table)))
1935 template))
1936
1937 (defun yas/define-snippets-1 (snippet snippet-table)
1938 "Helper for `yas/define-snippets'."
1939 ;; X) Calculate some more defaults on the values returned by
1940 ;; `yas/parse-template'.
1941 ;;
1942 (let* ((file (seventh snippet))
1943 (key (or (car snippet)
1944 (unless yas/ignore-filenames-as-triggers
1945 (and file
1946 (file-name-sans-extension (file-name-nondirectory file))))))
1947 (name (or (third snippet)
1948 (and file
1949 (file-name-directory file))))
1950 (condition (fourth snippet))
1951 (group (fifth snippet))
1952 (keybinding (yas/read-keybinding (eighth snippet)))
1953 (uuid (or (ninth snippet)
1954 name))
1955 (template (or (gethash uuid (yas/table-uuidhash snippet-table))
1956 (yas/make-blank-template))))
1957 ;; X) populate the template object
1958 ;;
1959 (yas/populate-template template
1960 :table snippet-table
1961 :key key
1962 :content (second snippet)
1963 :name (or name key)
1964 :group group
1965 :condition condition
1966 :expand-env (sixth snippet)
1967 :file (seventh snippet)
1968 :keybinding keybinding
1969 :uuid uuid)
1970 ;; X) Update this template in the appropriate table. This step
1971 ;; also will take care of adding the key indicators in the
1972 ;; templates menu entry, if any
1973 ;;
1974 (yas/update-template snippet-table template)
1975 ;; X) Return the template
1976 ;;
1977 ;;
1978 template))
1979
1980 (defun yas/snippet-menu-binding-pair-get-create (template &optional type)
1981 "Get TEMPLATE's menu binding or assign it a new one."
1982 (or (yas/template-menu-binding-pair template)
1983 (let ((key (yas/template-key template))
1984 (keybinding (yas/template-keybinding template)))
1985 (setf (yas/template-menu-binding-pair template)
1986 (cons `(menu-item ,(or (yas/template-name template)
1987 (yas/template-uuid template))
1988 ,(yas/make-menu-binding template)
1989 :keys ,nil)
1990 type)))))
1991
1992 (defun yas/show-menu-p (mode)
1993 (cond ((eq yas/use-menu 'abbreviate)
1994 (find mode
1995 (mapcar #'(lambda (table)
1996 (intern (yas/table-name table)))
1997 (yas/get-snippet-tables))))
1998 ((eq yas/use-menu 'real-modes)
1999 (yas/real-mode? mode))
2000 (t
2001 t)))
2002
2003 (defun yas/delete-from-keymap (keymap uuid)
2004 "Recursively delete items with UUID from KEYMAP and its submenus."
2005
2006 ;; XXX: This used to skip any submenus named \"parent mode\"
2007 ;;
2008 ;; First of all, recursively enter submenus, i.e. the tree is
2009 ;; searched depth first so that stale submenus can be found in the
2010 ;; higher passes.
2011 ;;
2012 (mapc #'(lambda (item)
2013 (when (and (listp (cdr item))
2014 (keymapp (third (cdr item))))
2015 (yas/delete-from-keymap (third (cdr item)) uuid)))
2016 (rest keymap))
2017 ;; Set the uuid entry to nil
2018 ;;
2019 (define-key keymap (vector (make-symbol uuid)) nil)
2020 ;; Destructively modify keymap
2021 ;;
2022 (setcdr keymap (delete-if #'(lambda (item)
2023 (or (null (cdr item))
2024 (and (keymapp (third (cdr item)))
2025 (null (cdr (third (cdr item)))))))
2026 (rest keymap))))
2027
2028 (defun yas/define-menu (mode menu omit-items)
2029 "Define a snippet menu for MODE according to MENU, ommitting OMIT-ITEMS.
2030
2031 MENU is a list, its elements can be:
2032
2033 - (yas/item UUID) : Creates an entry the snippet identified with
2034 UUID. The menu entry for a snippet thus identified is
2035 permanent, i.e. it will never move in the menu.
2036
2037 - (yas/separator) : Creates a separator
2038
2039 - (yas/submenu NAME SUBMENU) : Creates a submenu with NAME,
2040 SUBMENU has the same form as MENU. NAME is also added to the
2041 list of groups of the snippets defined thereafter.
2042
2043 OMIT-ITEMS is a list of snippet uuid's that will always be
2044 ommited from MODE's menu, even if they're manually loaded.
2045 "
2046 (let* ((table (yas/table-get-create mode))
2047 (hash (yas/table-uuidhash table)))
2048 (yas/define-menu-1 table
2049 (yas/menu-keymap-get-create table)
2050 menu
2051 hash)
2052 (dolist (uuid omit-items)
2053 (let ((template (or (gethash uuid hash)
2054 (yas/populate-template (puthash uuid
2055 (yas/make-blank-template)
2056 hash)
2057 :table table
2058 :uuid uuid))))
2059 (setf (yas/template-menu-binding-pair template) (cons nil :none))))))
2060
2061 (defun yas/define-menu-1 (table keymap menu uuidhash &optional group-list)
2062 (dolist (e (reverse menu))
2063 (cond ((eq (first e) 'yas/item)
2064 (let ((template (or (gethash (second e) uuidhash)
2065 (yas/populate-template (puthash (second e)
2066 (yas/make-blank-template)
2067 uuidhash)
2068 :table table
2069 :perm-group group-list
2070 :uuid (second e)))))
2071 (define-key keymap (vector (make-symbol (second e)))
2072 (car (yas/snippet-menu-binding-pair-get-create template :stay)))))
2073 ((eq (first e) 'yas/submenu)
2074 (let ((subkeymap (make-sparse-keymap)))
2075 (define-key keymap (vector (make-symbol(second e)))
2076 `(menu-item ,(second e) ,subkeymap))
2077 (yas/define-menu-1 table
2078 subkeymap
2079 (third e)
2080 uuidhash
2081 (append group-list (list (second e))))))
2082 ((eq (first e) 'yas/separator)
2083 (define-key keymap (vector (gensym))
2084 '(menu-item "----")))
2085 (t
2086 (message "[yas] don't know anything about menu entry %s" (first e))))))
2087
2088 (defun yas/define (mode key template &optional name condition group)
2089 "Define a snippet. Expanding KEY into TEMPLATE.
2090
2091 NAME is a description to this template. Also update the menu if
2092 `yas/use-menu' is `t'. CONDITION is the condition attached to
2093 this snippet. If you attach a condition to a snippet, then it
2094 will only be expanded when the condition evaluated to non-nil."
2095 (yas/define-snippets mode
2096 (list (list key template name condition group))))
2097
2098 (defun yas/hippie-try-expand (first-time?)
2099 "Integrate with hippie expand. Just put this function in
2100 `hippie-expand-try-functions-list'."
2101 (if (not first-time?)
2102 (let ((yas/fallback-behavior 'return-nil))
2103 (yas/expand))
2104 (undo 1)
2105 nil))
2106
2107
2108 ;;; Apropos condition-cache:
2109 ;;;
2110 ;;;
2111 ;;;
2112 ;;;
2113 (defvar yas/condition-cache-timestamp nil)
2114 (defmacro yas/define-condition-cache (func doc &rest body)
2115 "Define a function FUNC with doc DOC and body BODY, BODY is
2116 executed at most once every snippet expansion attempt, to check
2117 expansion conditions.
2118
2119 It doesn't make any sense to call FUNC programatically."
2120 `(defun ,func () ,(if (and doc
2121 (stringp doc))
2122 (concat doc
2123 "\n\nFor use in snippets' conditions. Within each
2124 snippet-expansion routine like `yas/expand', computes actual
2125 value for the first time then always returns a cached value.")
2126 (setq body (cons doc body))
2127 nil)
2128 (let ((timestamp-and-value (get ',func 'yas/condition-cache)))
2129 (if (equal (car timestamp-and-value) yas/condition-cache-timestamp)
2130 (cdr timestamp-and-value)
2131 (let ((new-value (progn
2132 ,@body
2133 )))
2134 (put ',func 'yas/condition-cache (cons yas/condition-cache-timestamp new-value))
2135 new-value)))))
2136
2137 (defalias 'yas/expand 'yas/expand-from-trigger-key)
2138 (defun yas/expand-from-trigger-key (&optional field)
2139 "Expand a snippet before point.
2140
2141 If no snippet expansion is possible, fall back to the behaviour
2142 defined in `yas/fallback-behavior'.
2143
2144 Optional argument FIELD is for non-interactive use and is an
2145 object satisfying `yas/field-p' to restrict the expansion to."
2146 (interactive)
2147 (setq yas/condition-cache-timestamp (current-time))
2148 (let (templates-and-pos)
2149 (unless (and yas/expand-only-for-last-commands
2150 (not (member last-command yas/expand-only-for-last-commands)))
2151 (setq templates-and-pos (if field
2152 (save-restriction
2153 (narrow-to-region (yas/field-start field)
2154 (yas/field-end field))
2155 (yas/current-key))
2156 (yas/current-key))))
2157 (if (and templates-and-pos
2158 (first templates-and-pos))
2159 (yas/expand-or-prompt-for-template (first templates-and-pos)
2160 (second templates-and-pos)
2161 (third templates-and-pos))
2162 (yas/fallback 'trigger-key))))
2163
2164 (defun yas/expand-from-keymap ()
2165 "Directly expand some snippets, searching `yas/direct-keymaps'.
2166
2167 If expansion fails, execute the previous binding for this key"
2168 (interactive)
2169 (setq yas/condition-cache-timestamp (current-time))
2170 (let* ((vec (this-command-keys-vector))
2171 (templates (mapcan #'(lambda (table)
2172 (yas/fetch table vec))
2173 (yas/get-snippet-tables))))
2174 (if templates
2175 (yas/expand-or-prompt-for-template templates)
2176 (let ((yas/fallback-behavior 'call-other-command))
2177 (yas/fallback)))))
2178
2179 (defun yas/expand-or-prompt-for-template (templates &optional start end)
2180 "Expand one of TEMPLATES from START to END.
2181
2182 Prompt the user if TEMPLATES has more than one element, else
2183 expand immediately. Common gateway for
2184 `yas/expand-from-trigger-key' and `yas/expand-from-keymap'."
2185 (let ((yas/current-template (or (and (rest templates) ;; more than one
2186 (yas/prompt-for-template (mapcar #'cdr templates)))
2187 (cdar templates))))
2188 (when yas/current-template
2189 (yas/expand-snippet (yas/template-content yas/current-template)
2190 start
2191 end
2192 (yas/template-expand-env yas/current-template)))))
2193
2194 (defun yas/fallback (&optional from-trigger-key-p)
2195 "Fallback after expansion has failed.
2196
2197 Common gateway for `yas/expand-from-trigger-key' and
2198 `yas/expand-from-keymap'."
2199 (cond ((eq yas/fallback-behavior 'return-nil)
2200 ;; return nil
2201 nil)
2202 ((eq yas/fallback-behavior 'call-other-command)
2203 (let* ((yas/minor-mode nil)
2204 (yas/direct-keymaps nil)
2205 (keys-1 (this-command-keys-vector))
2206 (keys-2 (and yas/trigger-key
2207 from-trigger-key-p
2208 (stringp yas/trigger-key)
2209 (read-kbd-macro yas/trigger-key)))
2210 (command-1 (and keys-1 (key-binding keys-1)))
2211 (command-2 (and keys-2 (key-binding keys-2)))
2212 ;; An (ugly) safety: prevents infinite recursion of
2213 ;; yas/expand* calls.
2214 (command (or (and (symbolp command-1)
2215 (not (string-match "yas/expand" (symbol-name command-1)))
2216 command-1)
2217 (and (symbolp command-2)
2218 command-2))))
2219 (when (and (commandp command)
2220 (not (string-match "yas/expand" (symbol-name command))))
2221 (setq this-command command)
2222 (call-interactively command))))
2223 ((and (listp yas/fallback-behavior)
2224 (cdr yas/fallback-behavior)
2225 (eq 'apply (car yas/fallback-behavior)))
2226 (if (cddr yas/fallback-behavior)
2227 (apply (cadr yas/fallback-behavior)
2228 (cddr yas/fallback-behavior))
2229 (when (commandp (cadr yas/fallback-behavior))
2230 (setq this-command (cadr yas/fallback-behavior))
2231 (call-interactively (cadr yas/fallback-behavior)))))
2232 (t
2233 ;; also return nil if all the other fallbacks have failed
2234 nil)))
2235
2236
2237 \f
2238 ;;; Snippet development
2239
2240 (defun yas/all-templates (tables)
2241 "Return all snippet tables applicable for the current buffer.
2242
2243 Honours `yas/choose-tables-first', `yas/choose-keys-first' and
2244 `yas/buffer-local-condition'"
2245 (when yas/choose-tables-first
2246 (setq tables (list (yas/prompt-for-table tables))))
2247 (mapcar #'cdr
2248 (if yas/choose-keys-first
2249 (let ((key (yas/prompt-for-keys
2250 (mapcan #'yas/table-all-keys tables))))
2251 (when key
2252 (mapcan #'(lambda (table)
2253 (yas/fetch table key))
2254 tables)))
2255 (remove-duplicates (mapcan #'yas/table-templates tables)
2256 :test #'equal))))
2257
2258 (defun yas/insert-snippet (&optional no-condition)
2259 "Choose a snippet to expand, pop-up a list of choices according
2260 to `yas/prompt-function'.
2261
2262 With prefix argument NO-CONDITION, bypass filtering of snippets
2263 by condition."
2264 (interactive "P")
2265 (setq yas/condition-cache-timestamp (current-time))
2266 (let* ((yas/buffer-local-condition (or (and no-condition
2267 'always)
2268 yas/buffer-local-condition))
2269 (templates (yas/all-templates (yas/get-snippet-tables)))
2270 (yas/current-template (and templates
2271 (or (and (rest templates) ;; more than one template for same key
2272 (yas/prompt-for-template templates))
2273 (car templates))))
2274 (where (if (region-active-p)
2275 (cons (region-beginning) (region-end))
2276 (cons (point) (point)))))
2277 (if yas/current-template
2278 (yas/expand-snippet (yas/template-content yas/current-template)
2279 (car where)
2280 (cdr where)
2281 (yas/template-expand-env yas/current-template))
2282 (message "[yas] No snippets can be inserted here!"))))
2283
2284 (defun yas/visit-snippet-file ()
2285 "Choose a snippet to edit, selection like `yas/insert-snippet'.
2286
2287 Only success if selected snippet was loaded from a file. Put the
2288 visited file in `snippet-mode'."
2289 (interactive)
2290 (let* ((yas/buffer-local-condition 'always)
2291 (templates (yas/all-templates (yas/get-snippet-tables)))
2292 (yas/prompt-functions '(yas/ido-prompt yas/completing-prompt))
2293 (template (and templates
2294 (or (yas/prompt-for-template templates
2295 "Choose a snippet template to edit: ")
2296 (car templates)))))
2297
2298 (if template
2299 (yas/visit-snippet-file-1 template)
2300 (message "No snippets tables active!"))))
2301
2302 (defun yas/visit-snippet-file-1 (template)
2303 (let ((file (yas/template-file template)))
2304 (cond ((and file (file-readable-p file))
2305 (find-file-other-window file)
2306 (snippet-mode)
2307 (set (make-local-variable 'yas/editing-template) template))
2308 (file
2309 (message "Original file %s no longer exists!" file))
2310 (t
2311 (switch-to-buffer (format "*%s*"(yas/template-name template)))
2312 (let ((type 'snippet))
2313 (when (listp (yas/template-content template))
2314 (insert (format "# type: command\n"))
2315 (setq type 'command))
2316 (insert (format "# key: %s\n" (yas/template-key template)))
2317 (insert (format "# name: %s\n" (yas/template-name template)))
2318 (when (yas/template-keybinding template)
2319 (insert (format "# binding: %s\n" (yas/template-keybinding template))))
2320 (when (yas/template-expand-env template)
2321 (insert (format "# expand-env: %s\n" (yas/template-expand-env template))))
2322 (when (yas/template-condition template)
2323 (insert (format "# condition: %s\n" (yas/template-condition template))))
2324 (insert "# --\n")
2325 (insert (if (eq type 'command)
2326 (pp-to-string (yas/template-content template))
2327 (yas/template-content template))))
2328 (snippet-mode)
2329 (set (make-local-variable 'yas/editing-template) template)))))
2330
2331 (defun yas/guess-snippet-directories-1 (table)
2332 "Guesses possible snippet subdirectories for TABLE."
2333 (cons (yas/table-name table)
2334 (mapcan #'(lambda (parent)
2335 (yas/guess-snippet-directories-1
2336 parent))
2337 (yas/table-parents table))))
2338
2339 (defun yas/guess-snippet-directories (&optional table)
2340 "Try to guess suitable directories based on the current active
2341 tables (or optional TABLE).
2342
2343 Returns a list of elemts (TABLE . DIRS) where TABLE is a
2344 `yas/table' object and DIRS is a list of all possible directories
2345 where snippets of table might exist."
2346 (let ((main-dir (replace-regexp-in-string
2347 "/+$" ""
2348 (or (first (or (yas/snippet-dirs)
2349 (setq yas/snippet-dirs '("~/.emacs.d/snippets")))))))
2350 (tables (or (and table
2351 (list table))
2352 (yas/get-snippet-tables))))
2353 ;; HACK! the snippet table created here is actually registered!
2354 ;;
2355 (unless (or table (gethash major-mode yas/tables))
2356 (push (yas/table-get-create major-mode)
2357 tables))
2358
2359 (mapcar #'(lambda (table)
2360 (cons table
2361 (mapcar #'(lambda (subdir)
2362 (concat main-dir "/" subdir))
2363 (yas/guess-snippet-directories-1 table))))
2364 tables)))
2365
2366 (defun yas/make-directory-maybe (table-and-dirs &optional main-table-string)
2367 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2368 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2369 (let ((candidate (first (cdr table-and-dirs))))
2370 (unless (file-writable-p (file-name-directory candidate))
2371 (error "[yas] %s is not writable." candidate))
2372 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2373 candidate
2374 (if (gethash (intern (yas/table-name (car table-and-dirs)))
2375 yas/tables)
2376 ""
2377 " brand new")
2378 (or main-table-string
2379 "")
2380 (yas/table-name (car table-and-dirs))))
2381 (progn
2382 (make-directory candidate 'also-make-parents)
2383 ;; create the .yas-parents file here...
2384 candidate)))))
2385
2386 (defun yas/new-snippet (&optional choose-instead-of-guess)
2387 ""
2388 (interactive "P")
2389 (let ((guessed-directories (yas/guess-snippet-directories)))
2390
2391 (switch-to-buffer "*new snippet*")
2392 (erase-buffer)
2393 (kill-all-local-variables)
2394 (snippet-mode)
2395 (set (make-local-variable 'yas/guessed-modes) (mapcar #'(lambda (d)
2396 (intern (yas/table-name (car d))))
2397 guessed-directories))
2398 (unless (and choose-instead-of-guess
2399 (not (y-or-n-p "Insert a snippet with useful headers? ")))
2400 (yas/expand-snippet "\
2401 # -*- mode: snippet -*-
2402 # name: $1
2403 # key: $2${3:
2404 # binding: ${4:direct-keybinding}}${5:
2405 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2406 # type: command}
2407 # --
2408 $0"))))
2409
2410 (defun yas/find-snippets (&optional same-window )
2411 "Find snippet file in guessed current mode's directory.
2412
2413 Calls `find-file' interactively in the guessed directory.
2414
2415 With prefix arg SAME-WINDOW opens the buffer in the same window.
2416
2417 Because snippets can be loaded from many different locations,
2418 this has to guess the correct directory using
2419 `yas/guess-snippet-directories', which returns a list of
2420 options.
2421
2422 If any one of these exists, it is taken and `find-file' is called
2423 there, otherwise, proposes to create the first option returned by
2424 `yas/guess-snippet-directories'."
2425 (interactive "P")
2426 (let* ((guessed-directories (yas/guess-snippet-directories))
2427 (chosen)
2428 (buffer))
2429 (setq chosen (yas/make-directory-maybe (first guessed-directories) " main"))
2430 (unless chosen
2431 (if (y-or-n-p (format "Continue guessing for other active tables %s? "
2432 (mapcar #'(lambda (table-and-dirs)
2433 (yas/table-name (car table-and-dirs)))
2434 (rest guessed-directories))))
2435 (setq chosen (some #'yas/make-directory-maybe
2436 (rest guessed-directories)))))
2437 (unless chosen
2438 (when (y-or-n-p "Having trouble... go to snippet root dir? ")
2439 (setq chosen (first (yas/snippet-dirs)))))
2440 (if chosen
2441 (let ((default-directory chosen))
2442 (setq buffer (call-interactively (if same-window
2443 'find-file
2444 'find-file-other-window)))
2445 (when buffer
2446 (save-excursion
2447 (set-buffer buffer)
2448 (when (eq major-mode 'fundamental-mode)
2449 (snippet-mode)))))
2450 (message "Could not guess snippet dir!"))))
2451
2452 (defun yas/compute-major-mode-and-parents (file &optional prompt-if-failed)
2453 (let* ((file-dir (and file
2454 (directory-file-name (or (some #'(lambda (special)
2455 (locate-dominating-file file special))
2456 '(".yas-setup.el"
2457 ".yas-make-groups"
2458 ".yas-parents"))
2459 (directory-file-name (file-name-directory file))))))
2460 (parents-file-name (concat file-dir "/.yas-parents"))
2461 (major-mode-name (and file-dir
2462 (file-name-nondirectory file-dir)))
2463 (major-mode-sym (or (and major-mode-name
2464 (intern major-mode-name))
2465 (when prompt-if-failed
2466 (read-from-minibuffer
2467 "[yas] Cannot auto-detect major mode! Enter a major mode: "))))
2468 (parents (when (file-readable-p parents-file-name)
2469 (mapcar #'intern
2470 (split-string
2471 (with-temp-buffer
2472 (insert-file-contents parents-file-name)
2473 (buffer-substring-no-properties (point-min)
2474 (point-max))))))))
2475 (when major-mode-sym
2476 (cons major-mode-sym parents))))
2477
2478 (defvar yas/editing-template nil
2479 "Supporting variable for `yas/load-snippet-buffer' and `yas/visit-snippet'")
2480
2481 (defvar yas/current-template nil
2482 "Holds the current template being expanded into a snippet.")
2483
2484 (defvar yas/guessed-modes nil
2485 "List of guessed modes supporting `yas/load-snippet-buffer'.")
2486
2487 (defun yas/load-snippet-buffer (&optional kill)
2488 "Parse and load current buffer's snippet definition.
2489
2490 With optional prefix argument KILL quit the window and buffer."
2491 (interactive "P")
2492 (let ((yas/ignore-filenames-as-triggers
2493 (or yas/ignore-filenames-as-triggers
2494 (and buffer-file-name
2495 (locate-dominating-file
2496 buffer-file-name
2497 ".yas-ignore-filenames-as-triggers")))))
2498 (cond
2499 ;; We have `yas/editing-template', this buffer's
2500 ;; content comes from a template which is already loaded and
2501 ;; neatly positioned,...
2502 ;;
2503 (yas/editing-template
2504 (yas/define-snippets-1 (yas/parse-template (yas/template-file yas/editing-template))
2505 (yas/template-table yas/editing-template)))
2506 ;; Try to use `yas/guessed-modes'. If we don't have that use the
2507 ;; value from `yas/compute-major-mode-and-parents'
2508 ;;
2509 (t
2510 (unless yas/guessed-modes
2511 (set (make-local-variable 'yas/guessed-modes) (or (yas/compute-major-mode-and-parents buffer-file-name))))
2512 (let* ((prompt (if (and (featurep 'ido)
2513 ido-mode)
2514 'ido-completing-read 'completing-read))
2515 (table (yas/table-get-create
2516 (intern
2517 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2518 (if yas/guessed-modes
2519 (first yas/guessed-modes)
2520 "nothing"))
2521 (mapcar #'symbol-name yas/guessed-modes)
2522 nil
2523 nil
2524 nil
2525 nil
2526 (if (first yas/guessed-modes)
2527 (symbol-name (first yas/guessed-modes))))))))
2528 (set (make-local-variable 'yas/editing-template)
2529 (yas/define-snippets-1 (yas/parse-template buffer-file-name)
2530 table))))))
2531 ;; Now, offer to save this shit
2532 ;;
2533 ;; 1) if `yas/snippet-dirs' is a list and its first element does not
2534 ;; match this template's file (i.e. this is a library snippet, not
2535 ;; a user snippet).
2536 ;;
2537 ;; 2) yas/editing-template comes from a file that we cannot write to...
2538 ;;
2539 (when (or (not (yas/template-file yas/editing-template))
2540 (not (file-writable-p (yas/template-file yas/editing-template)))
2541 (and (listp yas/snippet-dirs)
2542 (second yas/snippet-dirs)
2543 (not (string-match (expand-file-name (first yas/snippet-dirs))
2544 (yas/template-file yas/editing-template)))))
2545
2546 (when (y-or-n-p "[yas] Looks like a library or new snippet. Save to new file? ")
2547 (let* ((option (first (yas/guess-snippet-directories (yas/template-table yas/editing-template))))
2548 (chosen (and option
2549 (yas/make-directory-maybe option))))
2550 (when chosen
2551 (let ((default-file-name (or (and (yas/template-file yas/editing-template)
2552 (file-name-nondirectory (yas/template-file yas/editing-template)))
2553 (yas/template-name yas/editing-template))))
2554 (write-file (concat chosen "/"
2555 (read-from-minibuffer (format "File name to create in %s? " chosen)
2556 default-file-name)))
2557 (setf (yas/template-file yas/editing-template) buffer-file-name))))))
2558 (when kill
2559 (quit-window kill))
2560 (message "[yas] Snippet \"%s\" loaded for %s."
2561 (yas/template-name yas/editing-template)
2562 (yas/table-name (yas/template-table yas/editing-template))))
2563
2564
2565 (defun yas/tryout-snippet (&optional debug)
2566 "Test current buffers's snippet template in other buffer."
2567 (interactive "P")
2568 (let* ((major-mode-and-parent (yas/compute-major-mode-and-parents buffer-file-name))
2569 (parsed (yas/parse-template))
2570 (test-mode (or (and (car major-mode-and-parent)
2571 (fboundp (car major-mode-and-parent))
2572 (car major-mode-and-parent))
2573 (first yas/guessed-modes)
2574 (intern (read-from-minibuffer "[yas] please input a mode: "))))
2575 (yas/current-template
2576 (and parsed
2577 (fboundp test-mode)
2578 (yas/populate-template (yas/make-blank-template)
2579 :table nil ;; no tables for ephemeral snippets
2580 :key (first parsed)
2581 :content (second parsed)
2582 :name (third parsed)
2583 :expand-env (sixth parsed)))))
2584 (cond (yas/current-template
2585 (let ((buffer-name (format "*testing snippet: %s*" (yas/template-name yas/current-template))))
2586 (kill-buffer (get-buffer-create buffer-name))
2587 (switch-to-buffer (get-buffer-create buffer-name))
2588 (setq buffer-undo-list nil)
2589 (condition-case nil (funcall test-mode) (error nil))
2590 (yas/expand-snippet (yas/template-content yas/current-template)
2591 (point-min)
2592 (point-max)
2593 (yas/template-expand-env yas/current-template))
2594 (when (and debug
2595 (require 'yasnippet-debug nil t))
2596 (add-hook 'post-command-hook 'yas/debug-snippet-vars 't 'local))))
2597 (t
2598 (message "[yas] Cannot test snippet for unknown major mode")))))
2599
2600 (defun yas/template-fine-group (template)
2601 (car (last (or (yas/template-group template)
2602 (yas/template-perm-group template)))))
2603
2604 (defun yas/describe-tables (&optional choose)
2605 "Display snippets for each table."
2606 (interactive "P")
2607 (let* ((by-name-hash (and choose
2608 (y-or-n-p "Show by namehash? ")))
2609 (buffer (get-buffer-create "*YASnippet tables*"))
2610 (active-tables (yas/get-snippet-tables))
2611 (remain-tables (let ((all))
2612 (maphash #'(lambda (k v)
2613 (unless (find v active-tables)
2614 (push v all)))
2615 yas/tables)
2616 all))
2617 (table-lists (list active-tables remain-tables))
2618 (original-buffer (current-buffer))
2619 (continue t)
2620 (yas/condition-cache-timestamp (current-time)))
2621 (with-current-buffer buffer
2622 (setq buffer-read-only nil)
2623 (erase-buffer)
2624 (cond ((not by-name-hash)
2625 (insert "YASnippet tables: \n")
2626 (while (and table-lists
2627 continue)
2628 (dolist (table (car table-lists))
2629 (yas/describe-pretty-table table original-buffer))
2630 (setq table-lists (cdr table-lists))
2631 (when table-lists
2632 (yas/create-snippet-xrefs)
2633 (display-buffer buffer)
2634 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2635 (yas/create-snippet-xrefs)
2636 (help-mode)
2637 (goto-char 1))
2638 (t
2639 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2640 (dolist (table (append active-tables remain-tables))
2641 (insert (format "\nSnippet table `%s':\n\n" (yas/table-name table)))
2642 (let ((keys))
2643 (maphash #'(lambda (k v)
2644 (push k keys))
2645 (yas/table-hash table))
2646 (dolist (key keys)
2647 (insert (format " key %s maps snippets: %s\n" key
2648 (let ((names))
2649 (maphash #'(lambda (k v)
2650 (push k names))
2651 (gethash key (yas/table-hash table)))
2652 names))))))))
2653 (goto-char 1)
2654 (setq buffer-read-only t))
2655 (display-buffer buffer)))
2656
2657 (defun yas/describe-pretty-table (table &optional original-buffer)
2658 (insert (format "\nSnippet table `%s'"
2659 (yas/table-name table)))
2660 (if (yas/table-parents table)
2661 (insert (format " parents: %s\n"
2662 (mapcar #'yas/table-name
2663 (yas/table-parents table))))
2664 (insert "\n"))
2665 (insert (make-string 100 ?-) "\n")
2666 (insert "group state name key binding\n")
2667 (let ((groups-alist (list))
2668 group)
2669 (maphash #'(lambda (k v)
2670 (setq group (or (yas/template-fine-group v)
2671 "(top level)"))
2672 (when (yas/template-name v)
2673
2674 (aput 'groups-alist group (cons v (aget groups-alist group)))))
2675 (yas/table-uuidhash table))
2676 (dolist (group-and-templates groups-alist)
2677 (when (rest group-and-templates)
2678 (setq group (truncate-string-to-width (car group-and-templates) 25 0 ? "..."))
2679 (insert (make-string 100 ?-) "\n")
2680 (dolist (p (cdr group-and-templates))
2681 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas/template-name p))
2682 'yasnippet p)
2683 50 0 ? "..."))
2684 (group (prog1 group
2685 (setq group (make-string (length group) ? ))))
2686 (condition-string (let ((condition (yas/template-condition p)))
2687 (if (and condition
2688 original-buffer)
2689 (with-current-buffer original-buffer
2690 (if (yas/eval-condition condition)
2691 "(y)"
2692 "(s)"))
2693 "(a)"))))
2694 (insert group " ")
2695 (insert condition-string " ")
2696 (insert name
2697 (if (string-match "\\.\\.\\.$" name)
2698 "'"
2699 " ")
2700 " ")
2701 (insert (truncate-string-to-width (or (yas/template-key p) "")
2702 15 0 ? "...") " ")
2703 (insert (truncate-string-to-width (key-description (yas/template-keybinding p))
2704 15 0 ? "...") " ")
2705 (insert "\n")))))))
2706
2707
2708
2709
2710 \f
2711 ;;; User convenience functions, for using in snippet definitions
2712
2713 (defvar yas/modified-p nil
2714 "Non-nil if field has been modified by user or transformation.")
2715
2716 (defvar yas/moving-away-p nil
2717 "Non-nil if user is about to exit field.")
2718
2719 (defvar yas/text nil
2720 "Contains current field text.")
2721
2722 (defun yas/substr (str pattern &optional subexp)
2723 "Search PATTERN in STR and return SUBEXPth match.
2724
2725 If found, the content of subexp group SUBEXP (default 0) is
2726 returned, or else the original STR will be returned."
2727 (let ((grp (or subexp 0)))
2728 (save-match-data
2729 (if (string-match pattern str)
2730 (match-string-no-properties grp str)
2731 str))))
2732
2733 (defun yas/choose-value (possibilities)
2734 "Prompt for a string in the list POSSIBILITIES and return it."
2735 (unless (or yas/moving-away-p
2736 yas/modified-p)
2737 (some #'(lambda (fn)
2738 (funcall fn "Choose: " possibilities))
2739 yas/prompt-functions)))
2740
2741 (defun yas/key-to-value (alist)
2742 "Prompt for a string in the list POSSIBILITIES and return it."
2743 (unless (or yas/moving-away-p
2744 yas/modified-p)
2745 (let ((key (read-key-sequence "")))
2746 (when (stringp key)
2747 (or (cdr (find key alist :key #'car :test #'string=))
2748 key)))))
2749
2750 (defun yas/throw (text)
2751 "Throw a yas/exception with TEXT as the reason."
2752 (throw 'yas/exception (cons 'yas/exception text)))
2753
2754 (defun yas/verify-value (possibilities)
2755 "Verify that the current field value is in POSSIBILITIES
2756
2757 Otherwise throw exception."
2758 (when (and yas/moving-away-p (notany #'(lambda (pos) (string= pos yas/text)) possibilities))
2759 (yas/throw (format "[yas] field only allows %s" possibilities))))
2760
2761 (defun yas/field-value (number)
2762 "Get the string for field with NUMBER.
2763
2764 Use this in primary and mirror transformations to tget."
2765 (let* ((snippet (car (yas/snippets-at-point)))
2766 (field (and snippet
2767 (yas/snippet-find-field snippet number))))
2768 (when field
2769 (yas/field-text-for-display field))))
2770
2771 (defun yas/text ()
2772 "Return `yas/text' if that exists and is non-empty, else nil."
2773 (if (and yas/text
2774 (not (string= "" yas/text)))
2775 yas/text))
2776
2777 ;; (defun yas/selected-text ()
2778 ;; "Return `yas/selected-text' if that exists and is non-empty, else nil."
2779 ;; (if (and yas/selected-text
2780 ;; (not (string= "" yas/selected-text)))
2781 ;; yas/selected-text))
2782
2783 (defun yas/get-field-once (number &optional transform-fn)
2784 (unless yas/modified-p
2785 (if transform-fn
2786 (funcall transform-fn (yas/field-value number))
2787 (yas/field-value number))))
2788
2789 (defun yas/default-from-field (number)
2790 (unless yas/modified-p
2791 (yas/field-value number)))
2792
2793 (defun yas/inside-string ()
2794 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2795
2796 (defun yas/unimplemented (&optional missing-feature)
2797 (if yas/current-template
2798 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2799 (or missing-feature
2800 "something")))
2801 (yas/visit-snippet-file-1 yas/current-template))
2802 (message "No implementation. Missing %s" (or missing-feature "something"))))
2803
2804 \f
2805 ;;; Snippet expansion and field management
2806
2807 (defvar yas/active-field-overlay nil
2808 "Overlays the currently active field.")
2809
2810 (defvar yas/field-protection-overlays nil
2811 "Two overlays protect the current active field ")
2812
2813 (defconst yas/prefix nil
2814 "A prefix argument for expansion direct from keybindings")
2815
2816 (defvar yas/selected-text nil
2817 "The selected region deleted on the last snippet expansion.")
2818
2819 (defvar yas/start-column nil
2820 "The column where the snippet expansion started.")
2821
2822 (make-variable-buffer-local 'yas/active-field-overlay)
2823 (make-variable-buffer-local 'yas/field-protection-overlays)
2824 (put 'yas/active-field-overlay 'permanent-local t)
2825 (put 'yas/field-protection-overlays 'permanent-local t)
2826
2827 (defstruct (yas/snippet (:constructor yas/make-snippet ()))
2828 "A snippet.
2829
2830 ..."
2831 (fields '())
2832 (exit nil)
2833 (id (yas/snippet-next-id) :read-only t)
2834 (control-overlay nil)
2835 active-field
2836 ;; stacked expansion: the `previous-active-field' slot saves the
2837 ;; active field where the child expansion took place
2838 previous-active-field
2839 force-exit)
2840
2841 (defstruct (yas/field (:constructor yas/make-field (number start end parent-field)))
2842 "A field."
2843 number
2844 start end
2845 parent-field
2846 (mirrors '())
2847 (transform nil)
2848 (modified-p nil)
2849 next)
2850
2851 (defstruct (yas/mirror (:constructor yas/make-mirror (start end transform)))
2852 "A mirror."
2853 start end
2854 (transform nil)
2855 parent-field
2856 next)
2857
2858 (defstruct (yas/exit (:constructor yas/make-exit (marker)))
2859 marker
2860 next)
2861
2862 (defun yas/apply-transform (field-or-mirror field &optional empty-on-nil-p)
2863 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2864
2865 If there is no transform for ht field, return nil.
2866
2867 If there is a transform but it returns nil, return the empty
2868 string iff EMPTY-ON-NIL-P is true."
2869 (let* ((yas/text (yas/field-text-for-display field))
2870 (text yas/text)
2871 (yas/modified-p (yas/field-modified-p field))
2872 (yas/moving-away-p nil)
2873 (transform (if (yas/mirror-p field-or-mirror)
2874 (yas/mirror-transform field-or-mirror)
2875 (yas/field-transform field-or-mirror)))
2876 (start-point (if (yas/mirror-p field-or-mirror)
2877 (yas/mirror-start field-or-mirror)
2878 (yas/field-start field-or-mirror)))
2879 (transformed (and transform
2880 (save-excursion
2881 (goto-char start-point)
2882 (let ((ret (yas/eval-lisp transform)))
2883 (or ret (and empty-on-nil-p "")))))))
2884 transformed))
2885
2886 (defsubst yas/replace-all (from to &optional text)
2887 "Replace all occurance from FROM to TO.
2888
2889 With optional string TEXT do it in that string."
2890 (if text
2891 (replace-regexp-in-string (regexp-quote from) to text t t)
2892 (goto-char (point-min))
2893 (while (search-forward from nil t)
2894 (replace-match to t t text))))
2895
2896 (defun yas/snippet-find-field (snippet number)
2897 (find-if #'(lambda (field)
2898 (eq number (yas/field-number field)))
2899 (yas/snippet-fields snippet)))
2900
2901 (defun yas/snippet-sort-fields (snippet)
2902 "Sort the fields of SNIPPET in navigation order."
2903 (setf (yas/snippet-fields snippet)
2904 (sort (yas/snippet-fields snippet)
2905 #'yas/snippet-field-compare)))
2906
2907 (defun yas/snippet-field-compare (field1 field2)
2908 "Compare two fields. The field with a number is sorted first.
2909 If they both have a number, compare through the number. If neither
2910 have, compare through the field's start point"
2911 (let ((n1 (yas/field-number field1))
2912 (n2 (yas/field-number field2)))
2913 (if n1
2914 (if n2
2915 (or (zerop n2) (and (not (zerop n1))
2916 (< n1 n2)))
2917 (not (zerop n1)))
2918 (if n2
2919 (zerop n2)
2920 (< (yas/field-start field1)
2921 (yas/field-start field2))))))
2922
2923 (defun yas/field-probably-deleted-p (snippet field)
2924 "Guess if SNIPPET's FIELD should be skipped."
2925 (and (zerop (- (yas/field-start field) (yas/field-end field)))
2926 (or (yas/field-parent-field field)
2927 (and (eq field (car (last (yas/snippet-fields snippet))))
2928 (= (yas/field-start field) (overlay-end (yas/snippet-control-overlay snippet)))))
2929 ;; the field numbered 0, just before the exit marker, should
2930 ;; never be skipped
2931 (not (zerop (yas/field-number field)))))
2932
2933 (defun yas/snippets-at-point (&optional all-snippets)
2934 "Return a sorted list of snippets at point, most recently
2935 inserted first."
2936 (sort
2937 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
2938 (overlay-get ov 'yas/snippet))
2939 (if all-snippets
2940 (overlays-in (point-min) (point-max))
2941 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
2942 #'(lambda (s1 s2)
2943 (<= (yas/snippet-id s2) (yas/snippet-id s1)))))
2944
2945 (defun yas/next-field-or-maybe-expand ()
2946 "Try to expand a snippet at a key before point, otherwise
2947 delegate to `yas/next-field'."
2948 (interactive)
2949 (if yas/triggers-in-field
2950 (let ((yas/fallback-behavior 'return-nil)
2951 (active-field (overlay-get yas/active-field-overlay 'yas/field)))
2952 (when active-field
2953 (unless (yas/expand-from-trigger-key active-field)
2954 (yas/next-field))))
2955 (yas/next-field)))
2956
2957 (defun yas/next-field (&optional arg)
2958 "Navigate to next field. If there's none, exit the snippet."
2959 (interactive)
2960 (let* ((arg (or arg
2961 1))
2962 (snippet (first (yas/snippets-at-point)))
2963 (active-field (overlay-get yas/active-field-overlay 'yas/field))
2964 (live-fields (remove-if #'(lambda (field)
2965 (and (not (eq field active-field))
2966 (yas/field-probably-deleted-p snippet field)))
2967 (yas/snippet-fields snippet)))
2968 (active-field-pos (position active-field live-fields))
2969 (target-pos (and active-field-pos (+ arg active-field-pos)))
2970 (target-field (and target-pos (nth target-pos live-fields))))
2971 ;; First check if we're moving out of a field with a transform
2972 ;;
2973 (when (and active-field
2974 (yas/field-transform active-field))
2975 (let* ((yas/moving-away-p t)
2976 (yas/text (yas/field-text-for-display active-field))
2977 (text yas/text)
2978 (yas/modified-p (yas/field-modified-p active-field)))
2979 ;; primary field transform: exit call to field-transform
2980 (yas/eval-lisp (yas/field-transform active-field))))
2981 ;; Now actually move...
2982 (cond ((and target-pos (>= target-pos (length live-fields)))
2983 (yas/exit-snippet snippet))
2984 (target-field
2985 (yas/move-to-field snippet target-field))
2986 (t
2987 nil))))
2988
2989 (defun yas/place-overlays (snippet field)
2990 "Correctly place overlays for SNIPPET's FIELD"
2991 (yas/make-move-field-protection-overlays snippet field)
2992 (yas/make-move-active-field-overlay snippet field))
2993
2994 (defun yas/move-to-field (snippet field)
2995 "Update SNIPPET to move to field FIELD.
2996
2997 Also create some protection overlays"
2998 (goto-char (yas/field-start field))
2999 (yas/place-overlays snippet field)
3000 (overlay-put yas/active-field-overlay 'yas/field field)
3001 (let ((number (yas/field-number field)))
3002 ;; check for the special ${0: ...} field
3003 (if (and number (zerop number))
3004 (progn
3005 (set-mark (yas/field-end field))
3006 (setf (yas/snippet-force-exit snippet)
3007 (or (yas/field-transform field)
3008 t)))
3009 ;; make this field active
3010 (setf (yas/snippet-active-field snippet) field)
3011 ;; primary field transform: first call to snippet transform
3012 (unless (yas/field-modified-p field)
3013 (if (yas/field-update-display field snippet)
3014 (let ((inhibit-modification-hooks t))
3015 (yas/update-mirrors snippet))
3016 (setf (yas/field-modified-p field) nil))))))
3017
3018 (defun yas/prev-field ()
3019 "Navigate to prev field. If there's none, exit the snippet."
3020 (interactive)
3021 (yas/next-field -1))
3022
3023 (defun yas/abort-snippet (&optional snippet)
3024 (interactive)
3025 (let ((snippet (or snippet
3026 (car (yas/snippets-at-point)))))
3027 (when snippet
3028 (setf (yas/snippet-force-exit snippet) t))))
3029
3030 (defun yas/exit-snippet (snippet)
3031 "Goto exit-marker of SNIPPET."
3032 (interactive)
3033 (setf (yas/snippet-force-exit snippet) t)
3034 (goto-char (if (yas/snippet-exit snippet)
3035 (yas/exit-marker (yas/snippet-exit snippet))
3036 (overlay-end (yas/snippet-control-overlay snippet)))))
3037
3038 (defun yas/exit-all-snippets ()
3039 "Exit all snippets."
3040 (interactive)
3041 (mapc #'(lambda (snippet)
3042 (yas/exit-snippet snippet)
3043 (yas/check-commit-snippet))
3044 (yas/snippets-at-point)))
3045
3046 \f
3047 ;;; Some low level snippet-routines
3048
3049 (defun yas/commit-snippet (snippet)
3050 "Commit SNIPPET, but leave point as it is. This renders the
3051 snippet as ordinary text.
3052
3053 Return a buffer position where the point should be placed if
3054 exiting the snippet.
3055
3056 NO-HOOKS means don't run the `yas/after-exit-snippet-hook' hooks."
3057
3058 (let ((control-overlay (yas/snippet-control-overlay snippet))
3059 yas/snippet-beg
3060 yas/snippet-end)
3061 ;;
3062 ;; Save the end of the moribund snippet in case we need to revive it
3063 ;; its original expansion.
3064 ;;
3065 (when (and control-overlay
3066 (overlay-buffer control-overlay))
3067 (setq yas/snippet-beg (overlay-start control-overlay))
3068 (setq yas/snippet-end (overlay-end control-overlay))
3069 (delete-overlay control-overlay))
3070
3071 (let ((inhibit-modification-hooks t))
3072 (when yas/active-field-overlay
3073 (delete-overlay yas/active-field-overlay))
3074 (when yas/field-protection-overlays
3075 (mapc #'delete-overlay yas/field-protection-overlays)))
3076
3077 ;; stacked expansion: if the original expansion took place from a
3078 ;; field, make sure we advance it here at least to
3079 ;; `yas/snippet-end'...
3080 ;;
3081 (let ((previous-field (yas/snippet-previous-active-field snippet)))
3082 (when (and yas/snippet-end previous-field)
3083 (yas/advance-end-maybe previous-field yas/snippet-end)))
3084
3085 ;; Convert all markers to points,
3086 ;;
3087 (yas/markers-to-points snippet)
3088
3089 ;; Take care of snippet revival
3090 ;;
3091 (if yas/snippet-revival
3092 (push `(apply yas/snippet-revive ,yas/snippet-beg ,yas/snippet-end ,snippet)
3093 buffer-undo-list)
3094 ;; Dismember the snippet... this is useful if we get called
3095 ;; again from `yas/take-care-of-redo'....
3096 (setf (yas/snippet-fields snippet) nil)))
3097
3098 (message "[yas] snippet %s exited." (yas/snippet-id snippet)))
3099
3100 (defun yas/check-commit-snippet ()
3101 "Checks if point exited the currently active field of the
3102 snippet, if so cleans up the whole snippet up."
3103 (let* ((snippets (yas/snippets-at-point 'all-snippets))
3104 (snippets-left snippets)
3105 (snippet-exit-transform))
3106 (dolist (snippet snippets)
3107 (let ((active-field (yas/snippet-active-field snippet)))
3108 (setq snippet-exit-transform (yas/snippet-force-exit snippet))
3109 (cond ((or snippet-exit-transform
3110 (not (and active-field (yas/field-contains-point-p active-field))))
3111 (setq snippets-left (delete snippet snippets-left))
3112 (setf (yas/snippet-force-exit snippet) nil)
3113 (yas/commit-snippet snippet))
3114 ((and active-field
3115 (or (not yas/active-field-overlay)
3116 (not (overlay-buffer yas/active-field-overlay))))
3117 ;;
3118 ;; stacked expansion: this case is mainly for recent
3119 ;; snippet exits that place us back int the field of
3120 ;; another snippet
3121 ;;
3122 (save-excursion
3123 (yas/move-to-field snippet active-field)
3124 (yas/update-mirrors snippet)))
3125 (t
3126 nil))))
3127 (unless snippets-left
3128 (if snippet-exit-transform
3129 (yas/eval-lisp-no-saves snippet-exit-transform)
3130 (run-hooks 'yas/after-exit-snippet-hook)))))
3131
3132 ;; Apropos markers-to-points:
3133 ;;
3134 ;; This was found useful for performance reasons, so that an
3135 ;; excessive number of live markers aren't kept around in the
3136 ;; `buffer-undo-list'. However, in `markers-to-points', the
3137 ;; set-to-nil markers can't simply be discarded and replaced with
3138 ;; fresh ones in `points-to-markers'. The original marker that was
3139 ;; just set to nil has to be reused.
3140 ;;
3141 ;; This shouldn't bring horrible problems with undo/redo, but it
3142 ;; you never know
3143 ;;
3144 (defun yas/markers-to-points (snippet)
3145 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3146 where POINT is the original position of the marker and MARKER is
3147 the original marker object with the position set to nil."
3148 (dolist (field (yas/snippet-fields snippet))
3149 (let ((start (marker-position (yas/field-start field)))
3150 (end (marker-position (yas/field-end field))))
3151 (set-marker (yas/field-start field) nil)
3152 (set-marker (yas/field-end field) nil)
3153 (setf (yas/field-start field) (cons start (yas/field-start field)))
3154 (setf (yas/field-end field) (cons end (yas/field-end field))))
3155 (dolist (mirror (yas/field-mirrors field))
3156 (let ((start (marker-position (yas/mirror-start mirror)))
3157 (end (marker-position (yas/mirror-end mirror))))
3158 (set-marker (yas/mirror-start mirror) nil)
3159 (set-marker (yas/mirror-end mirror) nil)
3160 (setf (yas/mirror-start mirror) (cons start (yas/mirror-start mirror)))
3161 (setf (yas/mirror-end mirror) (cons end (yas/mirror-end mirror))))))
3162 (let ((snippet-exit (yas/snippet-exit snippet)))
3163 (when snippet-exit
3164 (let ((exit (marker-position (yas/exit-marker snippet-exit))))
3165 (set-marker (yas/exit-marker snippet-exit) nil)
3166 (setf (yas/exit-marker snippet-exit) (cons exit (yas/exit-marker snippet-exit)))))))
3167
3168 (defun yas/points-to-markers (snippet)
3169 "Convert all cons (POINT . MARKER) in SNIPPET to markers. This
3170 is done by setting MARKER to POINT with `set-marker'."
3171 (dolist (field (yas/snippet-fields snippet))
3172 (setf (yas/field-start field) (set-marker (cdr (yas/field-start field))
3173 (car (yas/field-start field))))
3174 (setf (yas/field-end field) (set-marker (cdr (yas/field-end field))
3175 (car (yas/field-end field))))
3176 (dolist (mirror (yas/field-mirrors field))
3177 (setf (yas/mirror-start mirror) (set-marker (cdr (yas/mirror-start mirror))
3178 (car (yas/mirror-start mirror))))
3179 (setf (yas/mirror-end mirror) (set-marker (cdr (yas/mirror-end mirror))
3180 (car (yas/mirror-end mirror))))))
3181 (let ((snippet-exit (yas/snippet-exit snippet)))
3182 (when snippet-exit
3183 (setf (yas/exit-marker snippet-exit) (set-marker (cdr (yas/exit-marker snippet-exit))
3184 (car (yas/exit-marker snippet-exit)))))))
3185
3186 (defun yas/field-contains-point-p (field &optional point)
3187 (let ((point (or point
3188 (point))))
3189 (and (>= point (yas/field-start field))
3190 (<= point (yas/field-end field)))))
3191
3192 (defun yas/field-text-for-display (field)
3193 "Return the propertized display text for field FIELD. "
3194 (buffer-substring (yas/field-start field) (yas/field-end field)))
3195
3196 (defun yas/undo-in-progress ()
3197 "True if some kind of undo is in progress"
3198 (or undo-in-progress
3199 (eq this-command 'undo)
3200 (eq this-command 'redo)))
3201
3202 (defun yas/make-control-overlay (snippet start end)
3203 "Creates the control overlay that surrounds the snippet and
3204 holds the keymap."
3205 (let ((overlay (make-overlay start
3206 end
3207 nil
3208 nil
3209 t)))
3210 (overlay-put overlay 'keymap yas/keymap)
3211 (overlay-put overlay 'yas/snippet snippet)
3212 overlay))
3213
3214 (defun yas/skip-and-clear-or-delete-char (&optional field)
3215 "Clears unmodified field if at field start, skips to next tab.
3216
3217 Otherwise deletes a character normally by calling `delete-char'."
3218 (interactive)
3219 (let ((field (or field
3220 (and yas/active-field-overlay
3221 (overlay-buffer yas/active-field-overlay)
3222 (overlay-get yas/active-field-overlay 'yas/field)))))
3223 (cond ((and field
3224 (not (yas/field-modified-p field))
3225 (eq (point) (marker-position (yas/field-start field))))
3226 (yas/skip-and-clear field)
3227 (yas/next-field 1))
3228 (t
3229 (call-interactively 'delete-char)))))
3230
3231 (defun yas/skip-and-clear (field)
3232 "Deletes the region of FIELD and sets it modified state to t"
3233 ;; Just before skipping-and-clearing the field, mark its children
3234 ;; fields as modified, too. If the childen have mirrors-in-fields
3235 ;; this prevents them from updating erroneously (we're skipping and
3236 ;; deleting!).
3237 ;;
3238 (yas/mark-this-and-children-modified field)
3239 (delete-region (yas/field-start field) (yas/field-end field)))
3240
3241 (defun yas/mark-this-and-children-modified (field)
3242 (setf (yas/field-modified-p field) t)
3243 (let ((fom (yas/field-next field)))
3244 (while (and fom
3245 (yas/fom-parent-field fom))
3246 (when (and (eq (yas/fom-parent-field fom) field)
3247 (yas/field-p fom))
3248 (yas/mark-this-and-children-modified fom))
3249 (setq fom (yas/fom-next fom)))))
3250
3251 (defun yas/make-move-active-field-overlay (snippet field)
3252 "Place the active field overlay in SNIPPET's FIELD.
3253
3254 Move the overlay, or create it if it does not exit."
3255 (if (and yas/active-field-overlay
3256 (overlay-buffer yas/active-field-overlay))
3257 (move-overlay yas/active-field-overlay
3258 (yas/field-start field)
3259 (yas/field-end field))
3260 (setq yas/active-field-overlay
3261 (make-overlay (yas/field-start field)
3262 (yas/field-end field)
3263 nil nil t))
3264 (overlay-put yas/active-field-overlay 'priority 100)
3265 (overlay-put yas/active-field-overlay 'face 'yas/field-highlight-face)
3266 (overlay-put yas/active-field-overlay 'yas/snippet snippet)
3267 (overlay-put yas/active-field-overlay 'modification-hooks '(yas/on-field-overlay-modification))
3268 (overlay-put yas/active-field-overlay 'insert-in-front-hooks
3269 '(yas/on-field-overlay-modification))
3270 (overlay-put yas/active-field-overlay 'insert-behind-hooks
3271 '(yas/on-field-overlay-modification))))
3272
3273 (defun yas/on-field-overlay-modification (overlay after? beg end &optional length)
3274 "Clears the field and updates mirrors, conditionally.
3275
3276 Only clears the field if it hasn't been modified and it point it
3277 at field start. This hook doesn't do anything if an undo is in
3278 progress."
3279 (unless (yas/undo-in-progress)
3280 (let* ((field (overlay-get overlay 'yas/field))
3281 (number (and field (yas/field-number field)))
3282 (snippet (overlay-get yas/active-field-overlay 'yas/snippet)))
3283 (cond (after?
3284 (yas/advance-end-maybe field (overlay-end overlay))
3285 (let ((saved-point (point)))
3286 (yas/field-update-display field (car (yas/snippets-at-point)))
3287 (goto-char saved-point))
3288 (yas/update-mirrors (car (yas/snippets-at-point))))
3289 (field
3290 (when (and (not after?)
3291 (not (yas/field-modified-p field))
3292 (eq (point) (if (markerp (yas/field-start field))
3293 (marker-position (yas/field-start field))
3294 (yas/field-start field))))
3295 (yas/skip-and-clear field))
3296 (setf (yas/field-modified-p field) t))))))
3297 \f
3298 ;;; Apropos protection overlays:
3299 ;;
3300 ;; These exist for nasty users who will try to delete parts of the
3301 ;; snippet outside the active field. Actual protection happens in
3302 ;; `yas/on-protection-overlay-modification'.
3303 ;;
3304 ;; Currently this signals an error which inhibits the command. For
3305 ;; commands that move point (like `kill-line'), point is restored in
3306 ;; the `yas/post-command-handler' using a global
3307 ;; `yas/protection-violation' variable.
3308 ;;
3309 ;; Alternatively, I've experimented with an implementation that
3310 ;; commits the snippet before actually calling `this-command'
3311 ;; interactively, and then signals an eror, which is ignored. but
3312 ;; blocks all other million modification hooks. This presented some
3313 ;; problems with stacked expansion.
3314 ;;
3315
3316 (defun yas/make-move-field-protection-overlays (snippet field)
3317 "Place protection overlays surrounding SNIPPET's FIELD.
3318
3319 Move the overlays, or create them if they do not exit."
3320 (let ((start (yas/field-start field))
3321 (end (yas/field-end field)))
3322 ;; First check if the (1+ end) is contained in the buffer,
3323 ;; otherwise we'll have to do a bit of cheating and silently
3324 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3325 ;; when using stacked expansion
3326 ;;
3327 (when (< (buffer-size) end)
3328 (save-excursion
3329 (let ((inhibit-modification-hooks t))
3330 (goto-char (point-max))
3331 (newline))))
3332 ;; go on to normal overlay creation/moving
3333 ;;
3334 (cond ((and yas/field-protection-overlays
3335 (every #'overlay-buffer yas/field-protection-overlays))
3336 (move-overlay (first yas/field-protection-overlays) (1- start) start)
3337 (move-overlay (second yas/field-protection-overlays) end (1+ end)))
3338 (t
3339 (setq yas/field-protection-overlays
3340 (list (make-overlay (1- start) start nil t nil)
3341 (make-overlay end (1+ end) nil t nil)))
3342 (dolist (ov yas/field-protection-overlays)
3343 (overlay-put ov 'face 'yas/field-debug-face)
3344 (overlay-put ov 'yas/snippet snippet)
3345 ;; (overlay-put ov 'evaporate t)
3346 (overlay-put ov 'modification-hooks '(yas/on-protection-overlay-modification)))))))
3347
3348 (defvar yas/protection-violation nil
3349 "When non-nil, signals attempts to erronesly exit or modify the snippet.
3350
3351 Functions in the `post-command-hook', for example
3352 `yas/post-command-handler' can check it and reset its value to
3353 nil. The variables value is the point where the violation
3354 originated")
3355
3356 (defun yas/on-protection-overlay-modification (overlay after? beg end &optional length)
3357 "Signals a snippet violation, then issues error.
3358
3359 The error should be ignored in `debug-ignored-errors'"
3360 (cond ((not (or after?
3361 (yas/undo-in-progress)))
3362 (setq yas/protection-violation (point))
3363 (error "Exit the snippet first!"))))
3364
3365 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3366
3367 \f
3368 ;;; Apropos stacked expansion:
3369 ;;
3370 ;; the parent snippet does not run its fields modification hooks
3371 ;; (`yas/on-field-overlay-modification' and
3372 ;; `yas/on-protection-overlay-modification') while the child snippet
3373 ;; is active. This means, among other things, that the mirrors of the
3374 ;; parent snippet are not updated, this only happening when one exits
3375 ;; the child snippet.
3376 ;;
3377 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3378 ;; bits of code in `yas/expand-snippet' and
3379 ;; `yas/commit-snippet'. I've tried to mark them with "stacked
3380 ;; expansion:".
3381 ;;
3382 ;; This was thought to be safer in in an undo/redo perpective, but
3383 ;; maybe the correct implementation is to make the globals
3384 ;; `yas/active-field-overlay' and `yas/field-protection-overlays' be
3385 ;; snippet-local and be active even while the child snippet is
3386 ;; running. This would mean a lot of overlay modification hooks
3387 ;; running, but if managed correctly (including overlay priorities)
3388 ;; they should account for all situations...
3389 ;;
3390
3391 (defun yas/expand-snippet (content &optional start end expand-env)
3392 "Expand snippet CONTENT at current point.
3393
3394 Text between START and END will be deleted before inserting
3395 template. EXPAND-ENV is are let-style variable to value bindings
3396 considered when expanding the snippet."
3397 (run-hooks 'yas/before-expand-snippet-hook)
3398
3399 ;; If a region is active, set `yas/selected-text'
3400 (setq yas/selected-text
3401 (when (region-active-p)
3402 (prog1 (buffer-substring-no-properties (region-beginning)
3403 (region-end))
3404 (unless start (setq start (region-beginning))
3405 (unless end (setq end (region-end)))))))
3406
3407 (when start
3408 (goto-char start))
3409
3410 ;;
3411 (let ((to-delete (and start end (buffer-substring-no-properties start end)))
3412 (start (or start (point)))
3413 (end (or end (point)))
3414 snippet)
3415 (setq yas/indent-original-column (current-column))
3416 ;; Delete the region to delete, this *does* get undo-recorded.
3417 ;;
3418 (when (and to-delete
3419 (> end start))
3420 (delete-region start end))
3421
3422 (cond ((listp content)
3423 ;; x) This is a snippet-command
3424 ;;
3425 (yas/eval-lisp-no-saves content))
3426 (t
3427 ;; x) This is a snippet-snippet :-)
3428 ;;
3429 ;; Narrow the region down to the content, shoosh the
3430 ;; `buffer-undo-list', and create the snippet, the new
3431 ;; snippet updates its mirrors once, so we are left with
3432 ;; some plain text. The undo action for deleting this
3433 ;; plain text will get recorded at the end.
3434 ;;
3435 ;; stacked expansion: also shoosh the overlay modification hooks
3436 (save-restriction
3437 (narrow-to-region start start)
3438 (let ((inhibit-modification-hooks t)
3439 (buffer-undo-list t))
3440 ;; snippet creation might evaluate users elisp, which
3441 ;; might generate errors, so we have to be ready to catch
3442 ;; them mostly to make the undo information
3443 ;;
3444 (setq yas/start-column (save-restriction (widen) (current-column)))
3445
3446 (setq snippet
3447 (if expand-env
3448 (eval `(let ,expand-env
3449 (insert content)
3450 (yas/snippet-create (point-min) (point-max))))
3451 (insert content)
3452 (yas/snippet-create (point-min) (point-max))))))
3453
3454 ;; stacked-expansion: This checks for stacked expansion, save the
3455 ;; `yas/previous-active-field' and advance its boudary.
3456 ;;
3457 (let ((existing-field (and yas/active-field-overlay
3458 (overlay-buffer yas/active-field-overlay)
3459 (overlay-get yas/active-field-overlay 'yas/field))))
3460 (when existing-field
3461 (setf (yas/snippet-previous-active-field snippet) existing-field)
3462 (yas/advance-end-maybe existing-field (overlay-end yas/active-field-overlay))))
3463
3464 ;; Exit the snippet immediately if no fields
3465 ;;
3466 (unless (yas/snippet-fields snippet)
3467 (yas/exit-snippet snippet))
3468
3469 ;; Push two undo actions: the deletion of the inserted contents of
3470 ;; the new snippet (without the "key") followed by an apply of
3471 ;; `yas/take-care-of-redo' on the newly inserted snippet boundaries
3472 ;;
3473 ;; A small exception, if `yas/also-auto-indent-first-line'
3474 ;; is t and `yas/indent' decides to indent the line to a
3475 ;; point before the actual expansion point, undo would be
3476 ;; messed up. We call the early point "newstart"". case,
3477 ;; and attempt to fix undo.
3478 ;;
3479 (let ((newstart (overlay-start (yas/snippet-control-overlay snippet)))
3480 (end (overlay-end (yas/snippet-control-overlay snippet))))
3481 (when (< newstart start)
3482 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3483 (push (cons newstart end) buffer-undo-list)
3484 (push `(apply yas/take-care-of-redo ,start ,end ,snippet)
3485 buffer-undo-list))
3486 ;; Now, schedule a move to the first field
3487 ;;
3488 (let ((first-field (car (yas/snippet-fields snippet))))
3489 (when first-field
3490 (sit-for 0) ;; fix issue 125
3491 (yas/move-to-field snippet first-field)))
3492 (message "[yas] snippet expanded.")
3493 t))))
3494
3495 (defun yas/take-care-of-redo (beg end snippet)
3496 "Commits SNIPPET, which in turn pushes an undo action for
3497 reviving it.
3498
3499 Meant to exit in the `buffer-undo-list'."
3500 ;; slightly optimize: this action is only needed for snippets with
3501 ;; at least one field
3502 (when (yas/snippet-fields snippet)
3503 (yas/commit-snippet snippet)))
3504
3505 (defun yas/snippet-revive (beg end snippet)
3506 "Revives the SNIPPET and creates a control overlay from BEG to
3507 END.
3508
3509 BEG and END are, we hope, the original snippets boudaries. All
3510 the markers/points exiting existing inside SNIPPET should point
3511 to their correct locations *at the time the snippet is revived*.
3512
3513 After revival, push the `yas/take-care-of-redo' in the
3514 `buffer-undo-list'"
3515 ;; Reconvert all the points to markers
3516 ;;
3517 (yas/points-to-markers snippet)
3518 ;; When at least one editable field existed in the zombie snippet,
3519 ;; try to revive the whole thing...
3520 ;;
3521 (let ((target-field (or (yas/snippet-active-field snippet)
3522 (car (yas/snippet-fields snippet)))))
3523 (when target-field
3524 (setf (yas/snippet-control-overlay snippet) (yas/make-control-overlay snippet beg end))
3525 (overlay-put (yas/snippet-control-overlay snippet) 'yas/snippet snippet)
3526
3527 (yas/move-to-field snippet target-field)
3528
3529 (push `(apply yas/take-care-of-redo ,beg ,end ,snippet)
3530 buffer-undo-list))))
3531
3532 (defun yas/snippet-create (begin end)
3533 "Creates a snippet from an template inserted between BEGIN and END.
3534
3535 Returns the newly created snippet."
3536 (let ((snippet (yas/make-snippet)))
3537 (goto-char begin)
3538 (yas/snippet-parse-create snippet)
3539
3540 ;; Sort and link each field
3541 (yas/snippet-sort-fields snippet)
3542
3543 ;; Create keymap overlay for snippet
3544 (setf (yas/snippet-control-overlay snippet)
3545 (yas/make-control-overlay snippet (point-min) (point-max)))
3546
3547 ;; Move to end
3548 (goto-char (point-max))
3549
3550 snippet))
3551
3552 \f
3553 ;;; Apropos adjacencies and "fom's":
3554 ;;
3555 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3556 ;; recently expanded snippet, we might actually have many fields,
3557 ;; mirrors (and the snippet exit) in the very same position in the
3558 ;; buffer. Therefore we need to single-link the
3559 ;; fields-or-mirrors-or-exit, which I have called "fom", according to
3560 ;; their original positions in the buffer.
3561 ;;
3562 ;; Then we have operation `yas/advance-end-maybe' and
3563 ;; `yas/advance-start-maybe', which conditionally push the starts and
3564 ;; ends of these foms down the chain.
3565 ;;
3566 ;; This allows for like the printf with the magic ",":
3567 ;;
3568 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3569 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3570 ;;
3571 (defun yas/fom-start (fom)
3572 (cond ((yas/field-p fom)
3573 (yas/field-start fom))
3574 ((yas/mirror-p fom)
3575 (yas/mirror-start fom))
3576 (t
3577 (yas/exit-marker fom))))
3578
3579 (defun yas/fom-end (fom)
3580 (cond ((yas/field-p fom)
3581 (yas/field-end fom))
3582 ((yas/mirror-p fom)
3583 (yas/mirror-end fom))
3584 (t
3585 (yas/exit-marker fom))))
3586
3587 (defun yas/fom-next (fom)
3588 (cond ((yas/field-p fom)
3589 (yas/field-next fom))
3590 ((yas/mirror-p fom)
3591 (yas/mirror-next fom))
3592 (t
3593 (yas/exit-next fom))))
3594
3595 (defun yas/fom-parent-field (fom)
3596 (cond ((yas/field-p fom)
3597 (yas/field-parent-field fom))
3598 ((yas/mirror-p fom)
3599 (yas/mirror-parent-field fom))
3600 (t
3601 nil)))
3602
3603 (defun yas/calculate-adjacencies (snippet)
3604 "Calculate adjacencies for fields or mirrors of SNIPPET.
3605
3606 This is according to their relative positions in the buffer, and
3607 has to be called before the $-constructs are deleted."
3608 (flet ((yas/fom-set-next-fom (fom nextfom)
3609 (cond ((yas/field-p fom)
3610 (setf (yas/field-next fom) nextfom))
3611 ((yas/mirror-p fom)
3612 (setf (yas/mirror-next fom) nextfom))
3613 (t
3614 (setf (yas/exit-next fom) nextfom))))
3615 (yas/compare-fom-begs (fom1 fom2)
3616 (if (= (yas/fom-start fom2) (yas/fom-start fom1))
3617 (yas/mirror-p fom2)
3618 (>= (yas/fom-start fom2) (yas/fom-start fom1))))
3619 (yas/link-foms (fom1 fom2)
3620 (yas/fom-set-next-fom fom1 fom2)))
3621 ;; make some yas/field, yas/mirror and yas/exit soup
3622 (let ((soup))
3623 (when (yas/snippet-exit snippet)
3624 (push (yas/snippet-exit snippet) soup))
3625 (dolist (field (yas/snippet-fields snippet))
3626 (push field soup)
3627 (dolist (mirror (yas/field-mirrors field))
3628 (push mirror soup)))
3629 (setq soup
3630 (sort soup
3631 #'yas/compare-fom-begs))
3632 (when soup
3633 (reduce #'yas/link-foms soup)))))
3634
3635 (defun yas/calculate-mirrors-in-fields (snippet mirror)
3636 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3637
3638 Use the tighest containing field if more than one field contains
3639 the mirror. Intended to be called *before* the dollar-regions are
3640 deleted."
3641 (let ((min (point-min))
3642 (max (point-max)))
3643 (dolist (field (yas/snippet-fields snippet))
3644 (when (and (<= (yas/field-start field) (yas/mirror-start mirror))
3645 (<= (yas/mirror-end mirror) (yas/field-end field))
3646 (< min (yas/field-start field))
3647 (< (yas/field-end field) max))
3648 (setq min (yas/field-start field)
3649 max (yas/field-end field))
3650 (setf (yas/mirror-parent-field mirror) field)))))
3651
3652 (defun yas/advance-end-maybe (fom newend)
3653 "Maybe advance FOM's end to NEWEND if it needs it.
3654
3655 If it does, also:
3656
3657 * call `yas/advance-start-maybe' on FOM's next fom.
3658
3659 * in case FOM is field call `yas/advance-end-maybe' on its parent
3660 field
3661
3662 Also, if FOM is an exit-marker, always call
3663 `yas/advance-start-maybe' on its next fom. This is beacuse
3664 exit-marker have identical start and end markers.
3665
3666 "
3667 (cond ((and fom (< (yas/fom-end fom) newend))
3668 (set-marker (yas/fom-end fom) newend)
3669 (yas/advance-start-maybe (yas/fom-next fom) newend)
3670 (let ((parent (yas/fom-parent-field fom)))
3671 (when parent
3672 (yas/advance-end-maybe parent newend))))
3673 ((yas/exit-p fom)
3674 (yas/advance-start-maybe (yas/fom-next fom) newend))))
3675
3676 (defun yas/advance-start-maybe (fom newstart)
3677 "Maybe advance FOM's start to NEWSTART if it needs it.
3678
3679 If it does, also call `yas/advance-end-maybe' on FOM."
3680 (when (and fom (< (yas/fom-start fom) newstart))
3681 (set-marker (yas/fom-start fom) newstart)
3682 (yas/advance-end-maybe fom newstart)))
3683
3684 (defun yas/advance-end-of-parents-maybe (field newend)
3685 "Like `yas/advance-end-maybe' but for parents."
3686 (when (and field
3687 (< (yas/field-end field) newend))
3688 (set-marker (yas/field-end field) newend)
3689 (yas/advance-end-of-parents-maybe (yas/field-parent-field field) newend)))
3690
3691 (defvar yas/dollar-regions nil
3692 "When expanding the snippet the \"parse-create\" functions add
3693 cons cells to this var")
3694
3695 (defun yas/snippet-parse-create (snippet)
3696 "Parse a recently inserted snippet template, creating all
3697 necessary fields, mirrors and exit points.
3698
3699 Meant to be called in a narrowed buffer, does various passes"
3700 (let ((parse-start (point)))
3701 ;; Reset the yas/dollar-regions
3702 ;;
3703 (setq yas/dollar-regions nil)
3704 ;; protect escaped quote, backquotes and backslashes
3705 ;;
3706 (yas/protect-escapes nil '(?\\ ?` ?'))
3707 ;; replace all backquoted expressions
3708 ;;
3709 (goto-char parse-start)
3710 (yas/replace-backquotes)
3711 ;; protect escapes again since previous steps might have generated
3712 ;; more characters needing escaping
3713 ;;
3714 (goto-char parse-start)
3715 (yas/protect-escapes)
3716 ;; parse fields with {}
3717 ;;
3718 (goto-char parse-start)
3719 (yas/field-parse-create snippet)
3720 ;; parse simple mirrors and fields
3721 ;;
3722 (goto-char parse-start)
3723 (yas/simple-mirror-parse-create snippet)
3724 ;; parse mirror transforms
3725 ;;
3726 (goto-char parse-start)
3727 (yas/transform-mirror-parse-create snippet)
3728 ;; calculate adjacencies of fields and mirrors
3729 ;;
3730 (yas/calculate-adjacencies snippet)
3731 ;; Delete $-constructs
3732 ;;
3733 (yas/delete-regions yas/dollar-regions)
3734 ;; restore escapes
3735 ;;
3736 (goto-char parse-start)
3737 (yas/restore-escapes)
3738 ;; update mirrors for the first time
3739 ;;
3740 (yas/update-mirrors snippet)
3741 ;; indent the best we can
3742 ;;
3743 (goto-char parse-start)
3744 (yas/indent snippet)))
3745
3746 (defun yas/indent-according-to-mode (snippet-markers)
3747 "Indent current line according to mode, preserving
3748 SNIPPET-MARKERS."
3749 ;;; Apropos indenting problems....
3750 ;;
3751 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3752 ;; is available. Some implementations of these functions delete text
3753 ;; before they insert. If there happens to be a marker just after
3754 ;; the text being deleted, the insertion actually happens after the
3755 ;; marker, which misplaces it.
3756 ;;
3757 ;; This would also happen if we had used overlays with the
3758 ;; `front-advance' property set to nil.
3759 ;;
3760 ;; This is why I have these `trouble-markers', they are the ones at
3761 ;; they are the ones at the first non-whitespace char at the line
3762 ;; (i.e. at `yas/real-line-beginning'. After indentation takes place
3763 ;; we should be at the correct to restore them to. All other
3764 ;; non-trouble-markers have been *pushed* and don't need special
3765 ;; attention.
3766 ;;
3767 (goto-char (yas/real-line-beginning))
3768 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3769 (= marker (point)))
3770 snippet-markers)))
3771 (save-restriction
3772 (widen)
3773 (condition-case err
3774 (indent-according-to-mode)
3775 (error (message "[yas] warning: yas/indent-according-to-mode habing problems running %s" indent-line-function)
3776 nil)))
3777 (mapc #'(lambda (marker)
3778 (set-marker marker (point)))
3779 trouble-markers)))
3780
3781 (defvar yas/indent-original-column nil)
3782 (defun yas/indent (snippet)
3783 (let ((snippet-markers (yas/collect-snippet-markers snippet)))
3784 ;; Look for those $>
3785 (save-excursion
3786 (while (re-search-forward "$>" nil t)
3787 (delete-region (match-beginning 0) (match-end 0))
3788 (when (not (eq yas/indent-line 'auto))
3789 (yas/indent-according-to-mode snippet-markers))))
3790 ;; Now do stuff for 'fixed and 'auto
3791 (save-excursion
3792 (cond ((eq yas/indent-line 'fixed)
3793 (while (and (zerop (forward-line))
3794 (zerop (current-column)))
3795 (indent-to-column yas/indent-original-column)))
3796 ((eq yas/indent-line 'auto)
3797 (let ((end (set-marker (make-marker) (point-max)))
3798 (indent-first-line-p yas/also-auto-indent-first-line))
3799 (while (and (zerop (if indent-first-line-p
3800 (prog1
3801 (forward-line 0)
3802 (setq indent-first-line-p nil))
3803 (forward-line 1)))
3804 (not (eobp))
3805 (<= (point) end))
3806 (yas/indent-according-to-mode snippet-markers))))
3807 (t
3808 nil)))))
3809
3810 (defun yas/collect-snippet-markers (snippet)
3811 "Make a list of all the markers used by SNIPPET."
3812 (let (markers)
3813 (dolist (field (yas/snippet-fields snippet))
3814 (push (yas/field-start field) markers)
3815 (push (yas/field-end field) markers)
3816 (dolist (mirror (yas/field-mirrors field))
3817 (push (yas/mirror-start mirror) markers)
3818 (push (yas/mirror-end mirror) markers)))
3819 (let ((snippet-exit (yas/snippet-exit snippet)))
3820 (when (and snippet-exit
3821 (marker-buffer (yas/exit-marker snippet-exit)))
3822 (push (yas/exit-marker snippet-exit) markers)))
3823 markers))
3824
3825 (defun yas/real-line-beginning ()
3826 (let ((c (char-after (line-beginning-position)))
3827 (n (line-beginning-position)))
3828 (while (or (eql c ?\ )
3829 (eql c ?\t))
3830 (incf n)
3831 (setq c (char-after n)))
3832 n))
3833
3834 (defun yas/escape-string (escaped)
3835 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3836
3837 (defun yas/protect-escapes (&optional text escaped)
3838 "Protect all escaped characters with their numeric ASCII value.
3839
3840 With optional string TEXT do it in string instead of buffer."
3841 (let ((changed-text text)
3842 (text-provided-p text))
3843 (mapc #'(lambda (escaped)
3844 (setq changed-text
3845 (yas/replace-all (concat "\\" (char-to-string escaped))
3846 (yas/escape-string escaped)
3847 (when text-provided-p changed-text))))
3848 (or escaped yas/escaped-characters))
3849 changed-text))
3850
3851 (defun yas/restore-escapes (&optional text escaped)
3852 "Restore all escaped characters from their numeric ASCII value.
3853
3854 With optional string TEXT do it in string instead of the buffer."
3855 (let ((changed-text text)
3856 (text-provided-p text))
3857 (mapc #'(lambda (escaped)
3858 (setq changed-text
3859 (yas/replace-all (yas/escape-string escaped)
3860 (char-to-string escaped)
3861 (when text-provided-p changed-text))))
3862 (or escaped yas/escaped-characters))
3863 changed-text))
3864
3865 (defun yas/replace-backquotes ()
3866 "Replace all the \"`(lisp-expression)`\"-style expression
3867 with their evaluated value"
3868 (while (re-search-forward yas/backquote-lisp-expression-regexp nil t)
3869 (let ((current-string (match-string 1)) transformed)
3870 (delete-region (match-beginning 0) (match-end 0))
3871 (setq transformed (yas/eval-lisp (yas/read-lisp (yas/restore-escapes current-string))))
3872 (goto-char (match-beginning 0))
3873 (when transformed (insert transformed)))))
3874
3875 (defun yas/scan-sexps (from count)
3876 (condition-case err
3877 (with-syntax-table (standard-syntax-table)
3878 (scan-sexps from count))
3879 (error
3880 nil)))
3881
3882 (defun yas/make-marker (pos)
3883 "Create a marker at POS with `nil' `marker-insertion-type'"
3884 (let ((marker (set-marker (make-marker) pos)))
3885 (set-marker-insertion-type marker nil)
3886 marker))
3887
3888 (defun yas/field-parse-create (snippet &optional parent-field)
3889 "Parse most field expressions, except for the simple one \"$n\".
3890
3891 The following count as a field:
3892
3893 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
3894
3895 * \"${n: text$(expression)}, the same with a lisp expression;
3896 this is caught with the curiously named `yas/multi-dollar-lisp-expression-regexp'
3897
3898 * the same as above but unnumbered, (no N:) and number is calculated automatically.
3899
3900 When multiple expressions are found, only the last one counts."
3901 ;;
3902 (save-excursion
3903 (while (re-search-forward yas/field-regexp nil t)
3904 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3905 (number (and (match-string-no-properties 1)
3906 (string-to-number (match-string-no-properties 1))))
3907 (brand-new-field (and real-match-end-0
3908 ;; break if on "$(" immediately
3909 ;; after the ":", this will be
3910 ;; caught as a mirror with
3911 ;; transform later.
3912 (not (save-match-data
3913 (eq (string-match "$[ \t\n]*("
3914 (match-string-no-properties 2)) 0)))
3915 ;; allow ${0: some exit text}
3916 ;; (not (and number (zerop number)))
3917 (yas/make-field number
3918 (yas/make-marker (match-beginning 2))
3919 (yas/make-marker (1- real-match-end-0))
3920 parent-field))))
3921 (when brand-new-field
3922 (goto-char real-match-end-0)
3923 (push (cons (1- real-match-end-0) real-match-end-0)
3924 yas/dollar-regions)
3925 (push (cons (match-beginning 0) (match-beginning 2))
3926 yas/dollar-regions)
3927 (push brand-new-field (yas/snippet-fields snippet))
3928 (save-excursion
3929 (save-restriction
3930 (narrow-to-region (yas/field-start brand-new-field) (yas/field-end brand-new-field))
3931 (goto-char (point-min))
3932 (yas/field-parse-create snippet brand-new-field)))))))
3933 ;; if we entered from a parent field, now search for the
3934 ;; `yas/multi-dollar-lisp-expression-regexp'. THis is used for
3935 ;; primary field transformations
3936 ;;
3937 (when parent-field
3938 (save-excursion
3939 (while (re-search-forward yas/multi-dollar-lisp-expression-regexp nil t)
3940 (let* ((real-match-end-1 (yas/scan-sexps (match-beginning 1) 1)))
3941 ;; commit the primary field transformation if:
3942 ;;
3943 ;; 1. we don't find it in yas/dollar-regions (a subnested
3944 ;; field) might have already caught it.
3945 ;;
3946 ;; 2. we really make sure we have either two '$' or some
3947 ;; text and a '$' after the colon ':'. This is a FIXME: work
3948 ;; my regular expressions and end these ugly hacks.
3949 ;;
3950 (when (and real-match-end-1
3951 (not (member (cons (match-beginning 0)
3952 real-match-end-1)
3953 yas/dollar-regions))
3954 (not (eq ?:
3955 (char-before (1- (match-beginning 1))))))
3956 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
3957 real-match-end-1)))
3958 (setf (yas/field-transform parent-field)
3959 (yas/read-lisp (yas/restore-escapes lisp-expression-string))))
3960 (push (cons (match-beginning 0) real-match-end-1)
3961 yas/dollar-regions)))))))
3962
3963 (defun yas/transform-mirror-parse-create (snippet)
3964 "Parse the \"${n:$(lisp-expression)}\" mirror transformations."
3965 (while (re-search-forward yas/transform-mirror-regexp nil t)
3966 (let* ((real-match-end-0 (yas/scan-sexps (1+ (match-beginning 0)) 1))
3967 (number (string-to-number (match-string-no-properties 1)))
3968 (field (and number
3969 (not (zerop number))
3970 (yas/snippet-find-field snippet number)))
3971 (brand-new-mirror
3972 (and real-match-end-0
3973 field
3974 (yas/make-mirror (yas/make-marker (match-beginning 0))
3975 (yas/make-marker (match-beginning 0))
3976 (yas/read-lisp
3977 (yas/restore-escapes
3978 (buffer-substring-no-properties (match-beginning 2)
3979 (1- real-match-end-0))))))))
3980 (when brand-new-mirror
3981 (push brand-new-mirror
3982 (yas/field-mirrors field))
3983 (yas/calculate-mirrors-in-fields snippet brand-new-mirror)
3984 (push (cons (match-beginning 0) real-match-end-0) yas/dollar-regions)))))
3985
3986 (defun yas/simple-mirror-parse-create (snippet)
3987 "Parse the simple \"$n\" fields/mirrors/exitmarkers."
3988 (while (re-search-forward yas/simple-mirror-regexp nil t)
3989 (let ((number (string-to-number (match-string-no-properties 1))))
3990 (cond ((zerop number)
3991
3992 (setf (yas/snippet-exit snippet)
3993 (yas/make-exit (yas/make-marker (match-end 0))))
3994 (save-excursion
3995 (goto-char (match-beginning 0))
3996 (when yas/wrap-around-region
3997 (cond (yas/selected-text
3998 (insert yas/selected-text))
3999 ((and (eq yas/wrap-around-region 'cua)
4000 cua-mode
4001 (get-register ?0))
4002 (insert (prog1 (get-register ?0)
4003 (set-register ?0 nil))))))
4004 (push (cons (point) (yas/exit-marker (yas/snippet-exit snippet)))
4005 yas/dollar-regions)))
4006 (t
4007 (let ((field (yas/snippet-find-field snippet number)))
4008 (if field
4009 (let ((brand-new-mirror (yas/make-mirror
4010 (yas/make-marker (match-beginning 0))
4011 (yas/make-marker (match-beginning 0))
4012 nil)))
4013 (push brand-new-mirror
4014 (yas/field-mirrors field))
4015 (yas/calculate-mirrors-in-fields snippet brand-new-mirror))
4016 (push (yas/make-field number
4017 (yas/make-marker (match-beginning 0))
4018 (yas/make-marker (match-beginning 0))
4019 nil)
4020 (yas/snippet-fields snippet))))
4021 (push (cons (match-beginning 0) (match-end 0))
4022 yas/dollar-regions))))))
4023
4024 (defun yas/delete-regions (regions)
4025 "Sort disjuct REGIONS by start point, then delete from the back."
4026 (mapc #'(lambda (reg)
4027 (delete-region (car reg) (cdr reg)))
4028 (sort regions
4029 #'(lambda (r1 r2)
4030 (>= (car r1) (car r2))))))
4031
4032 (defun yas/update-mirrors (snippet)
4033 "Updates all the mirrors of SNIPPET."
4034 (save-excursion
4035 (let* ((fields (copy-list (yas/snippet-fields snippet)))
4036 (field (car fields)))
4037 (while field
4038 (dolist (mirror (yas/field-mirrors field))
4039 ;; stacked expansion: I added an `inhibit-modification-hooks'
4040 ;; here, for safety, may need to remove if we the mechanism is
4041 ;; altered.
4042 ;;
4043 (let ((inhibit-modification-hooks t)
4044 (mirror-parent-field (yas/mirror-parent-field mirror)))
4045 ;; updatte this mirror
4046 ;;
4047 (yas/mirror-update-display mirror field)
4048 ;; for mirrors-in-fields: schedule a possible
4049 ;; parent field for reupdting later on
4050 ;;
4051 (when mirror-parent-field
4052 (add-to-list 'fields mirror-parent-field 'append #'eq))
4053 ;; `yas/place-overlays' is needed if the active field and
4054 ;; protected overlays have been changed because of insertions
4055 ;; in `yas/mirror-update-display'
4056 ;;
4057 (when (eq field (yas/snippet-active-field snippet))
4058 (yas/place-overlays snippet field))))
4059 (setq fields (cdr fields))
4060 (setq field (car fields))))))
4061
4062 (defun yas/mirror-update-display (mirror field)
4063 "Update MIRROR according to FIELD (and mirror transform)."
4064
4065 (let* ((mirror-parent-field (yas/mirror-parent-field mirror))
4066 (reflection (and (not (and mirror-parent-field
4067 (yas/field-modified-p mirror-parent-field)))
4068 (or (yas/apply-transform mirror field 'empty-on-nil)
4069 (yas/field-text-for-display field)))))
4070 (when (and reflection
4071 (not (string= reflection (buffer-substring-no-properties (yas/mirror-start mirror)
4072 (yas/mirror-end mirror)))))
4073 (goto-char (yas/mirror-start mirror))
4074 (insert reflection)
4075 (if (> (yas/mirror-end mirror) (point))
4076 (delete-region (point) (yas/mirror-end mirror))
4077 (set-marker (yas/mirror-end mirror) (point))
4078 (yas/advance-start-maybe (yas/mirror-next mirror) (point))
4079 ;; super-special advance
4080 (yas/advance-end-of-parents-maybe mirror-parent-field (point))))))
4081
4082 (defun yas/field-update-display (field snippet)
4083 "Much like `yas/mirror-update-display', but for fields"
4084 (when (yas/field-transform field)
4085 (let ((inhibit-modification-hooks t)
4086 (transformed (and (not (eq (yas/field-number field) 0))
4087 (yas/apply-transform field field)))
4088 (point (point)))
4089 (when (and transformed
4090 (not (string= transformed (buffer-substring-no-properties (yas/field-start field)
4091 (yas/field-end field)))))
4092 (setf (yas/field-modified-p field) t)
4093 (goto-char (yas/field-start field))
4094 (insert transformed)
4095 (if (> (yas/field-end field) (point))
4096 (delete-region (point) (yas/field-end field))
4097 (set-marker (yas/field-end field) (point))
4098 (yas/advance-start-maybe (yas/field-next field) (point)))
4099 t))))
4100
4101 \f
4102 ;;; Post-command hooks:
4103
4104 (defvar yas/post-command-runonce-actions nil
4105 "List of actions to run once `post-command-hook'.
4106
4107 Each element of this list looks like (FN . ARGS) where FN is
4108 called with ARGS as its arguments after the currently executing
4109 snippet command.
4110
4111 After all actions have been run, this list is emptied, and after
4112 that the rest of `yas/post-command-handler' runs.")
4113
4114 (defun yas/post-command-handler ()
4115 "Handles various yasnippet conditions after each command."
4116 (when yas/post-command-runonce-actions
4117 (condition-case err
4118 (mapc #'(lambda (fn-and-args)
4119 (apply (car fn-and-args)
4120 (cdr fn-and-args)))
4121 yas/post-command-runonce-actions)
4122 (error (message "[yas] problem running `yas/post-command-runonce-actions'!")))
4123 (setq yas/post-command-runonce-actions nil))
4124 (cond (yas/protection-violation
4125 (goto-char yas/protection-violation)
4126 (setq yas/protection-violation nil))
4127 ((eq 'undo this-command)
4128 ;;
4129 ;; After undo revival the correct field is sometimes not
4130 ;; restored correctly, this condition handles that
4131 ;;
4132 (let* ((snippet (car (yas/snippets-at-point)))
4133 (target-field (and snippet
4134 (find-if-not #'(lambda (field)
4135 (yas/field-probably-deleted-p snippet field))
4136 (remove nil
4137 (cons (yas/snippet-active-field snippet)
4138 (yas/snippet-fields snippet)))))))
4139 (when target-field
4140 (yas/move-to-field snippet target-field))))
4141 ((not (yas/undo-in-progress))
4142 ;; When not in an undo, check if we must commit the snippet
4143 ;; (user exited it).
4144 (yas/check-commit-snippet))))
4145 \f
4146 ;;; Fancy docs:
4147
4148 (put 'yas/expand 'function-documentation
4149 '(yas/expand-from-trigger-key-doc))
4150 (defun yas/expand-from-trigger-key-doc ()
4151 "A doc synthethizer for `yas/expand-from-trigger-key-doc'."
4152 (let ((fallback-description
4153 (cond ((eq yas/fallback-behavior 'call-other-command)
4154 (let* ((yas/minor-mode nil)
4155 (fallback (key-binding (read-kbd-macro yas/trigger-key))))
4156 (or (and fallback
4157 (format " call command `%s'." (pp-to-string fallback)))
4158 " do nothing.")))
4159 ((eq yas/fallback-behavior 'return-nil)
4160 ", do nothing.")
4161 (t
4162 ", defer to `yas/fallback-behaviour' :-)"))))
4163 (concat "Expand a snippet before point. If no snippet
4164 expansion is possible,"
4165 fallback-description
4166 "\n\nOptional argument FIELD is for non-interactive use and is an
4167 object satisfying `yas/field-p' to restrict the expansion to.")))
4168
4169 (put 'yas/expand-from-keymap 'function-documentation '(yas/expand-from-keymap-doc))
4170 (defun yas/expand-from-keymap-doc ()
4171 "A doc synthethizer for `yas/expand-from-keymap-doc'."
4172 (add-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce)
4173 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4174 (when (eq this-command 'describe-key)
4175 (let* ((vec (this-single-command-keys))
4176 (templates (mapcan #'(lambda (table)
4177 (yas/fetch table vec))
4178 (yas/get-snippet-tables)))
4179 (yas/direct-keymaps nil)
4180 (fallback (key-binding vec)))
4181 (concat "In this case, "
4182 (when templates
4183 (concat "these snippets are bound to this key:\n"
4184 (yas/template-pretty-list templates)
4185 "\n\nIf none of these expands, "))
4186 (or (and fallback
4187 (format "fallback `%s' will be called." (pp-to-string fallback)))
4188 "no fallback keybinding is called."))))))
4189
4190 (defun yas/template-pretty-list (templates)
4191 (let ((acc)
4192 (yas/buffer-local-condition 'always))
4193 (dolist (plate templates)
4194 (setq acc (concat acc "\n*) "
4195 (propertize (concat "\\\\snippet `" (car plate) "'")
4196 'yasnippet (cdr plate)))))
4197 acc))
4198
4199 (define-button-type 'help-snippet-def
4200 :supertype 'help-xref
4201 'help-function (lambda (template) (yas/visit-snippet-file-1 template))
4202 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4203
4204 (defun yas/snippet-description-finish-runonce ()
4205 "Final adjustments for the help buffer when snippets are concerned."
4206 (yas/create-snippet-xrefs)
4207 (remove-hook 'temp-buffer-show-hook 'yas/snippet-description-finish-runonce))
4208
4209 (defun yas/create-snippet-xrefs ()
4210 (save-excursion
4211 (goto-char (point-min))
4212 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4213 (let ((template (get-text-property (match-beginning 1)
4214 'yasnippet)))
4215 (when template
4216 (help-xref-button 1 'help-snippet-def template)
4217 (kill-region (match-end 1) (match-end 0))
4218 (kill-region (match-beginning 0) (match-beginning 1)))))))
4219
4220 (defun yas/expand-uuid (mode-symbol uuid &optional start end expand-env)
4221 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4222
4223 Remaining args as in `yas/expand-snippet'."
4224 (let* ((table (gethash mode-symbol yas/tables))
4225 (yas/current-template (and table
4226 (gethash uuid (yas/table-uuidhash table)))))
4227 (when yas/current-template
4228 (yas/expand-snippet (yas/template-content yas/current-template)))))
4229
4230 \f
4231 ;;; Some hacks:
4232 ;; `locate-dominating-file' is added for compatibility in emacs < 23
4233 (unless (or (eq emacs-major-version 23)
4234 (fboundp 'locate-dominating-file))
4235 (defvar locate-dominating-stop-dir-regexp
4236 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4237 "Regexp of directory names which stop the search in `locate-dominating-file'.
4238 Any directory whose name matches this regexp will be treated like
4239 a kind of root directory by `locate-dominating-file' which will stop its search
4240 when it bumps into it.
4241 The default regexp prevents fruitless and time-consuming attempts to find
4242 special files in directories in which filenames are interpreted as hostnames,
4243 or mount points potentially requiring authentication as a different user.")
4244
4245 (defun locate-dominating-file (file name)
4246 "Look up the directory hierarchy from FILE for a file named NAME.
4247 Stop at the first parent directory containing a file NAME,
4248 and return the directory. Return nil if not found."
4249 ;; We used to use the above locate-dominating-files code, but the
4250 ;; directory-files call is very costly, so we're much better off doing
4251 ;; multiple calls using the code in here.
4252 ;;
4253 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4254 ;; `name' in /home or in /.
4255 (setq file (abbreviate-file-name file))
4256 (let ((root nil)
4257 (prev-file file)
4258 ;; `user' is not initialized outside the loop because
4259 ;; `file' may not exist, so we may have to walk up part of the
4260 ;; hierarchy before we find the "initial UUID".
4261 (user nil)
4262 try)
4263 (while (not (or root
4264 (null file)
4265 ;; FIXME: Disabled this heuristic because it is sometimes
4266 ;; inappropriate.
4267 ;; As a heuristic, we stop looking up the hierarchy of
4268 ;; directories as soon as we find a directory belonging
4269 ;; to another user. This should save us from looking in
4270 ;; things like /net and /afs. This assumes that all the
4271 ;; files inside a project belong to the same user.
4272 ;; (let ((prev-user user))
4273 ;; (setq user (nth 2 (file-attributes file)))
4274 ;; (and prev-user (not (equal user prev-user))))
4275 (string-match locate-dominating-stop-dir-regexp file)))
4276 (setq try (file-exists-p (expand-file-name name file)))
4277 (cond (try (setq root file))
4278 ((equal file (setq prev-file file
4279 file (file-name-directory
4280 (directory-file-name file))))
4281 (setq file nil))))
4282 root)))
4283
4284 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4285 ;; (when it execute forward-char) and interrupt the after change
4286 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4287 ;; invoked. Here's a way to reproduce it:
4288
4289 ;; # open a *new* Emacs.
4290 ;; # load yasnippet.
4291 ;; # open a *new* .cpp file.
4292 ;; # input "inc" and press TAB to expand the snippet.
4293 ;; # select the `#include <...>` snippet.
4294 ;; # type inside `<>`
4295
4296 (defadvice c-neutralize-syntax-in-CPP
4297 (around yas-mp/c-neutralize-syntax-in-CPP activate)
4298 "Adviced `c-neutralize-syntax-in-CPP' to properly
4299 handle the end-of-buffer error fired in it by calling
4300 `forward-char' at the end of buffer."
4301 (condition-case err
4302 ad-do-it
4303 (error (message (error-message-string err)))))
4304
4305 ;; disable c-electric-* serial command in YAS fields
4306 (add-hook 'c-mode-common-hook
4307 '(lambda ()
4308 (dolist (k '(":" ">" ";" "<" "{" "}"))
4309 (define-key (symbol-value (make-local-variable 'yas/keymap))
4310 k 'self-insert-command))))
4311
4312 (provide 'yasnippet)
4313
4314 ;;; yasnippet.el ends here