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