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