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