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