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