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