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