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