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