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