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