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