]> code.delx.au - gnu-emacs-elpa/blob - yasnippet.el
closes #391: don't assume `declare-function'/ exists, it doesn't in emacs22
[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 (eval-when-compile
1627 (if (fboundp 'declare-function)
1628 (declare-function dropdown-list "dropdown-list")))
1629
1630 (defun yas-dropdown-prompt (prompt choices &optional display-fn)
1631 (when (featurep 'dropdown-list)
1632 (let (formatted-choices
1633 filtered-choices
1634 d
1635 n)
1636 (dolist (choice choices)
1637 (setq d (or (and display-fn (funcall display-fn choice))
1638 choice))
1639 (when (stringp d)
1640 (push d formatted-choices)
1641 (push choice filtered-choices)))
1642
1643 (setq n (and formatted-choices (dropdown-list formatted-choices)))
1644 (if n
1645 (nth n filtered-choices)
1646 (keyboard-quit)))))
1647
1648 (defun yas-completing-prompt (prompt choices &optional display-fn completion-fn)
1649 (let (formatted-choices
1650 filtered-choices
1651 chosen
1652 d
1653 (completion-fn (or completion-fn
1654 #'completing-read)))
1655 (dolist (choice choices)
1656 (setq d (or (and display-fn (funcall display-fn choice))
1657 choice))
1658 (when (stringp d)
1659 (push d formatted-choices)
1660 (push choice filtered-choices)))
1661 (setq chosen (and formatted-choices
1662 (funcall completion-fn prompt
1663 formatted-choices
1664 nil
1665 'require-match
1666 nil
1667 nil)))
1668 (let ((position (or (and chosen
1669 (position chosen formatted-choices :test #'string=))
1670 0)))
1671 (nth position filtered-choices))))
1672
1673 (defun yas-no-prompt (prompt choices &optional display-fn)
1674 (first choices))
1675
1676 \f
1677 ;;; Defining snippets
1678 ;; This consists of creating and registering `yas--template' objects in the
1679 ;; correct tables.
1680 ;;
1681
1682 (defun yas--define-snippets-1 (snippet snippet-table)
1683 "Helper for `yas-define-snippets'."
1684 ;; X) Calculate some more defaults on the values returned by
1685 ;; `yas--parse-template'.
1686 ;;
1687 (let* ((file (seventh snippet))
1688 (key (car snippet))
1689 (name (or (third snippet)
1690 (and file
1691 (file-name-directory file))))
1692 (condition (fourth snippet))
1693 (group (fifth snippet))
1694 (keybinding (yas--read-keybinding (eighth snippet)))
1695 (uuid (or (ninth snippet)
1696 name))
1697 (template (or (gethash uuid (yas--table-uuidhash snippet-table))
1698 (yas--make-blank-template))))
1699 ;; X) populate the template object
1700 ;;
1701 (yas--populate-template template
1702 :table snippet-table
1703 :key key
1704 :content (second snippet)
1705 :name (or name key)
1706 :group group
1707 :condition condition
1708 :expand-env (sixth snippet)
1709 :file (seventh snippet)
1710 :keybinding keybinding
1711 :uuid uuid)
1712 ;; X) Update this template in the appropriate table. This step
1713 ;; also will take care of adding the key indicators in the
1714 ;; templates menu entry, if any
1715 ;;
1716 (yas--update-template snippet-table template)
1717 ;; X) Return the template
1718 ;;
1719 ;;
1720 template))
1721
1722 (defun yas-define-snippets (mode snippets)
1723 "Define SNIPPETS for MODE.
1724
1725 SNIPPETS is a list of snippet definitions, each taking the
1726 following form
1727
1728 (KEY TEMPLATE NAME CONDITION GROUP EXPAND-ENV FILE KEYBINDING UUID)
1729
1730 Within these, only KEY and TEMPLATE are actually mandatory.
1731
1732 TEMPLATE might be a lisp form or a string, depending on whether
1733 this is a snippet or a snippet-command.
1734
1735 CONDITION, EXPAND-ENV and KEYBINDING are lisp forms, they have
1736 been `yas--read-lisp'-ed and will eventually be
1737 `yas--eval-lisp'-ed.
1738
1739 The remaining elements are strings.
1740
1741 FILE is probably of very little use if you're programatically
1742 defining snippets.
1743
1744 UUID is the snippets \"unique-id\". Loading a second snippet file
1745 with the same uuid replaced the previous snippet.
1746
1747 You can use `yas--parse-template' to return such lists based on
1748 the current buffers contents."
1749 (let ((snippet-table (yas--table-get-create mode))
1750 (template nil))
1751 (dolist (snippet snippets)
1752 (setq template (yas--define-snippets-1 snippet
1753 snippet-table)))
1754 template))
1755
1756 \f
1757 ;;; Loading snippets from files
1758
1759 (defun yas--load-yas-setup-file (file)
1760 (load file 'noerror))
1761
1762 (defun yas--define-parents (mode parents)
1763 "Add PARENTS to the list of MODE's parents."
1764 (puthash mode (remove-duplicates
1765 (append parents
1766 (gethash mode yas--parents)))
1767 yas--parents))
1768
1769 (defun yas-load-directory (top-level-dir &optional use-jit)
1770 "Load snippets in directory hierarchy TOP-LEVEL-DIR.
1771
1772 Below TOP-LEVEL-DIR each directory should be a mode name.
1773
1774 Optional USE-JIT use jit-loading of snippets."
1775 (interactive "DSelect the root directory: ")
1776 (unless yas-snippet-dirs
1777 (setq yas-snippet-dirs top-level-dir))
1778 (dolist (dir (yas--subdirs top-level-dir))
1779 (let* ((major-mode-and-parents (yas--compute-major-mode-and-parents
1780 (concat dir "/dummy")))
1781 (mode-sym (car major-mode-and-parents))
1782 (parents (cdr major-mode-and-parents)))
1783 ;; Attention: The parents and the menus are already defined
1784 ;; here, even if the snippets are later jit-loaded.
1785 ;;
1786 ;; * We need to know the parents at this point since entering a
1787 ;; given mode should jit load for its parents
1788 ;; immediately. This could be reviewed, the parents could be
1789 ;; discovered just-in-time-as well
1790 ;;
1791 ;; * We need to create the menus here to support the `full'
1792 ;; option to `yas-use-menu' (all known snippet menus are shown to the user)
1793 ;;
1794 (yas--define-parents mode-sym parents)
1795 (yas--menu-keymap-get-create mode-sym)
1796 (let ((form `(yas--load-directory-1 ,dir
1797 ',mode-sym
1798 ',parents)))
1799 (if (and use-jit
1800 (not (some #'(lambda (buffer)
1801 (with-current-buffer buffer
1802 (when (eq major-mode mode-sym)
1803 (yas--message 3 "Discovered there was already %s in %s" buffer mode-sym)
1804 t)))
1805 (buffer-list))))
1806 (yas--schedule-jit mode-sym form)
1807 (eval form)))))
1808 (when (yas--called-interactively-p 'interactive)
1809 (yas--message 3 "Loaded snippets from %s." top-level-dir)))
1810
1811 (defun yas--load-directory-1 (directory mode-sym parents &optional no-compiled-snippets)
1812 "Recursively load snippet templates from DIRECTORY."
1813 (unless (file-exists-p (concat directory "/" ".yas-skip"))
1814 (if (and (not no-compiled-snippets)
1815 (progn (yas--message 2 "Loading compiled snippets from %s" directory) t)
1816 (load (expand-file-name ".yas-compiled-snippets" directory) 'noerror (<= yas-verbosity 3)))
1817 (yas--message 2 "Loading snippet files from %s" directory)
1818 (yas--load-directory-2 directory mode-sym))))
1819
1820 (defun yas--load-directory-2 (directory mode-sym)
1821 ;; Load .yas-setup.el files wherever we find them
1822 ;;
1823 (yas--load-yas-setup-file (expand-file-name ".yas-setup" directory))
1824 (let* ((default-directory directory)
1825 (snippet-defs nil))
1826 ;; load the snippet files
1827 ;;
1828 (with-temp-buffer
1829 (dolist (file (yas--subdirs directory 'no-subdirs-just-files))
1830 (when (file-readable-p file)
1831 (insert-file-contents file nil nil nil t)
1832 (push (yas--parse-template file)
1833 snippet-defs))))
1834 (when snippet-defs
1835 (yas-define-snippets mode-sym
1836 snippet-defs))
1837 ;; now recurse to a lower level
1838 ;;
1839 (dolist (subdir (yas--subdirs directory))
1840 (yas--load-directory-2 subdir
1841 mode-sym))))
1842
1843 (defun yas--load-snippet-dirs (&optional nojit)
1844 "Reload the directories listed in `yas-snippet-dirs' or
1845 prompt the user to select one."
1846 (let (errors)
1847 (if yas-snippet-dirs
1848 (dolist (directory (reverse (yas-snippet-dirs)))
1849 (cond ((file-directory-p directory)
1850 (yas-load-directory directory (not nojit))
1851 (if nojit
1852 (yas--message 3 "Loaded %s" directory)
1853 (yas--message 3 "Prepared just-in-time loading for %s" directory)))
1854 (t
1855 (push (yas--message 0 "Check your `yas-snippet-dirs': %s is not a directory" directory) errors))))
1856 (call-interactively 'yas-load-directory))
1857 errors))
1858
1859 (defun yas-reload-all (&optional interactive)
1860 "Reload all snippets and rebuild the YASnippet menu.
1861
1862 When called interactively force immediate reload of all known
1863 snippets under `yas-snippet-dirs', otherwise use just-in-time
1864 loading."
1865 (interactive "p")
1866 (catch 'abort
1867 (let ((errors)
1868 (snippet-editing-buffers
1869 (remove-if-not #'(lambda (buffer)
1870 (with-current-buffer buffer yas--editing-template))
1871 (buffer-list))))
1872 ;; Warn if there are buffers visiting snippets, since reloading will break
1873 ;; any on-line editing of those buffers.
1874 ;;
1875 (when snippet-editing-buffers
1876 (if interactive
1877 (if (y-or-n-p "Some buffers editing live snippets, close them and proceed with reload? ")
1878 (mapc #'kill-buffer snippet-editing-buffers)
1879 (yas--message 1 "Aborted reload...")
1880 (throw 'abort nil))
1881 ;; in a non-interactive use, at least set
1882 ;; `yas--editing-template' to nil, make it guess it next time around
1883 (mapc #'(lambda (buffer) (setq yas--editing-template nil)) (buffer-list))))
1884
1885 ;; Empty all snippet tables and parenting info
1886 ;;
1887 (setq yas--tables (make-hash-table))
1888 (setq yas--parents (make-hash-table))
1889 (setq yas--ancestors (make-hash-table))
1890
1891 ;; Before killing `yas--menu-table' use its keys to cleanup the
1892 ;; mode menu parts of `yas--minor-mode-menu' (thus also cleaning
1893 ;; up `yas-minor-mode-map', which points to it)
1894 ;;
1895 (maphash #'(lambda (menu-symbol keymap)
1896 (define-key yas--minor-mode-menu (vector menu-symbol) nil))
1897 yas--menu-table)
1898 ;; Now empty `yas--menu-table' as well
1899 (setq yas--menu-table (make-hash-table))
1900
1901 ;; Cancel all pending 'yas--scheduled-jit-loads'
1902 ;;
1903 (setq yas--scheduled-jit-loads (make-hash-table))
1904
1905 ;; Reload the directories listed in `yas-snippet-dirs' or prompt
1906 ;; the user to select one.
1907 ;;
1908 (setq errors (yas--load-snippet-dirs interactive))
1909 ;; Reload the direct keybindings
1910 ;;
1911 (yas-direct-keymaps-reload)
1912
1913 (yas--message 3 "Reloaded everything%s...%s."
1914 (if interactive "" " (snippets will load just-in-time)")
1915 (if errors " (some errors, check *Messages*)" "")))))
1916
1917 (defun yas--load-pending-jits ()
1918 (dolist (mode (yas--modes-to-activate))
1919 (let ((forms (reverse (gethash mode yas--scheduled-jit-loads))))
1920 ;; must reverse to maintain coherence with `yas-snippet-dirs'
1921 (dolist (form forms)
1922 (yas--message 3 "Loading for `%s', just-in-time: %s!" mode form)
1923 (eval form))
1924 (remhash mode yas--scheduled-jit-loads))))
1925
1926 ;; (when (<= emacs-major-version 22)
1927 ;; (add-hook 'after-change-major-mode-hook 'yas--load-pending-jits))
1928
1929 (defun yas--quote-string (string)
1930 "Escape and quote STRING.
1931 foo\"bar\\! -> \"foo\\\"bar\\\\!\""
1932 (concat "\""
1933 (replace-regexp-in-string "[\\\"]"
1934 "\\\\\\&"
1935 string
1936 t)
1937 "\""))
1938 \f
1939 ;;; Snippet compilation function
1940
1941 (defun yas--initialize ()
1942 "For backward compatibility, enable `yas-minor-mode' globally."
1943 (yas-global-mode 1))
1944
1945 (defun yas-compile-directory (top-level-dir)
1946 "Create .yas-compiled-snippets.el files under subdirs of TOP-LEVEL-DIR.
1947
1948 This works by stubbing a few functions, then calling
1949 `yas-load-directory'."
1950 (interactive "DTop level snippet directory?")
1951 (yas--with-temporary-redefinitions
1952 ((yas--load-yas-setup-file
1953 (file)
1954 (let ((elfile (concat file ".el")))
1955 (when (file-exists-p elfile)
1956 (insert ";;; .yas-setup.el support file if any:\n;;;\n")
1957 (insert-file-contents elfile)
1958 (goto-char (point-max))
1959 )))
1960 (yas-define-snippets
1961 (mode snippets)
1962 (insert ";;; Snippet definitions:\n;;;\n")
1963 (let ((literal-snippets (list))
1964 (print-length nil))
1965 (dolist (snippet snippets)
1966 (let ((key (first snippet))
1967 (template-content (second snippet))
1968 (name (third snippet))
1969 (condition (fourth snippet))
1970 (group (fifth snippet))
1971 (expand-env (sixth snippet))
1972 (file nil) ;; (seventh snippet)) ;; omit on purpose
1973 (binding (eighth snippet))
1974 (uuid (ninth snippet)))
1975 (push `(,key
1976 ,template-content
1977 ,name
1978 ,condition
1979 ,group
1980 ,expand-env
1981 ,file
1982 ,binding
1983 ,uuid)
1984 literal-snippets)))
1985 (insert (pp-to-string `(yas-define-snippets ',mode ',literal-snippets)))
1986 (insert "\n\n")))
1987 (yas--load-directory-1
1988 (dir mode parents &rest ignore)
1989 (let ((output-file (concat (file-name-as-directory dir) ".yas-compiled-snippets.el")))
1990 (with-temp-file output-file
1991 (insert (format ";;; Compiled snippets and support files for `%s'\n" mode))
1992 (yas--load-directory-2 dir mode)
1993 (insert (format ";;; Do not edit! File generated at %s\n" (current-time-string)))))))
1994 (yas-load-directory top-level-dir nil)))
1995
1996 (defun yas-recompile-all ()
1997 "Compile every dir in `yas-snippet-dirs'."
1998 (interactive)
1999 (mapc #'yas-compile-directory (yas-snippet-dirs)))
2000
2001
2002 ;;; JIT loading
2003 ;;;
2004
2005 (defvar yas--scheduled-jit-loads (make-hash-table)
2006 "Alist of mode-symbols to forms to be evaled when `yas-minor-mode' kicks in.")
2007
2008 (defun yas--schedule-jit (mode form)
2009 (puthash mode
2010 (cons form
2011 (gethash mode yas--scheduled-jit-loads))
2012 yas--scheduled-jit-loads))
2013
2014
2015 \f
2016 ;;; Some user level functions
2017
2018 (defun yas-about ()
2019 (interactive)
2020 (message (concat "yasnippet (version "
2021 yas--version
2022 ") -- pluskid <pluskid@gmail.com>/joaotavora <joaotavora@gmail.com>")))
2023
2024 \f
2025 ;;; Apropos snippet menu:
2026 ;;
2027 ;; The snippet menu keymaps are store by mode in hash table called
2028 ;; `yas--menu-table'. They are linked to the main menu in
2029 ;; `yas--menu-keymap-get-create' and are initially created empty,
2030 ;; reflecting the table hierarchy.
2031 ;;
2032 ;; They can be populated in two mutually exclusive ways: (1) by
2033 ;; reading `yas--template-group', which in turn is populated by the "#
2034 ;; group:" directives of the snippets or the ".yas-make-groups" file
2035 ;; or (2) by using a separate `yas-define-menu' call, which declares a
2036 ;; menu structure based on snippets uuids.
2037 ;;
2038 ;; Both situations are handled in `yas--update-template-menu', which
2039 ;; uses the predicate `yas--template-menu-managed-by-yas-define-menu'
2040 ;; that can tell between the two situations.
2041 ;;
2042 ;; Note:
2043 ;;
2044 ;; * if `yas-define-menu' is used it must run before
2045 ;; `yas-define-snippets' and the UUIDS must match, otherwise we get
2046 ;; duplicate entries. The `yas--template' objects are created in
2047 ;; `yas-define-menu', holding nothing but the menu entry,
2048 ;; represented by a pair of ((menu-item NAME :keys KEYS) TYPE) and
2049 ;; stored in `yas--template-menu-binding-pair'. The (menu-item ...)
2050 ;; part is then stored in the menu keymap itself which make the item
2051 ;; appear to the user. These limitations could probably be revised.
2052 ;;
2053 ;; * The `yas--template-perm-group' slot is only used in
2054 ;; `yas-describe-tables'.
2055 ;;
2056 (defun yas--template-menu-binding-pair-get-create (template &optional type)
2057 "Get TEMPLATE's menu binding or assign it a new one.
2058
2059 TYPE may be `:stay', signaling this menu binding should be
2060 static in the menu."
2061 (or (yas--template-menu-binding-pair template)
2062 (let ((key (yas--template-key template))
2063 (keybinding (yas--template-keybinding template)))
2064 (setf (yas--template-menu-binding-pair template)
2065 (cons `(menu-item ,(or (yas--template-name template)
2066 (yas--template-uuid template))
2067 ,(yas--make-menu-binding template)
2068 :keys ,nil)
2069 type)))))
2070 (defun yas--template-menu-managed-by-yas-define-menu (template)
2071 "Non-nil if TEMPLATE's menu entry was included in a `yas-define-menu' call."
2072 (cdr (yas--template-menu-binding-pair template)))
2073
2074
2075 (defun yas--show-menu-p (mode)
2076 (cond ((eq yas-use-menu 'abbreviate)
2077 (find mode
2078 (mapcar #'(lambda (table)
2079 (yas--table-mode table))
2080 (yas--get-snippet-tables))))
2081 ((eq yas-use-menu 'full)
2082 t)
2083 ((eq yas-use-menu t)
2084 t)))
2085
2086 (defun yas--delete-from-keymap (keymap uuid)
2087 "Recursively delete items with UUID from KEYMAP and its submenus."
2088
2089 ;; XXX: This used to skip any submenus named \"parent mode\"
2090 ;;
2091 ;; First of all, recursively enter submenus, i.e. the tree is
2092 ;; searched depth first so that stale submenus can be found in the
2093 ;; higher passes.
2094 ;;
2095 (mapc #'(lambda (item)
2096 (when (and (listp (cdr item))
2097 (keymapp (third (cdr item))))
2098 (yas--delete-from-keymap (third (cdr item)) uuid)))
2099 (rest keymap))
2100 ;; Set the uuid entry to nil
2101 ;;
2102 (define-key keymap (vector (make-symbol uuid)) nil)
2103 ;; Destructively modify keymap
2104 ;;
2105 (setcdr keymap (delete-if #'(lambda (item)
2106 (or (null (cdr item))
2107 (and (keymapp (third (cdr item)))
2108 (null (cdr (third (cdr item)))))))
2109 (rest keymap))))
2110
2111 (defun yas-define-menu (mode menu &optional omit-items)
2112 "Define a snippet menu for MODE according to MENU, omitting OMIT-ITEMS.
2113
2114 MENU is a list, its elements can be:
2115
2116 - (yas-item UUID) : Creates an entry the snippet identified with
2117 UUID. The menu entry for a snippet thus identified is
2118 permanent, i.e. it will never move (be reordered) in the menu.
2119
2120 - (yas-separator) : Creates a separator
2121
2122 - (yas-submenu NAME SUBMENU) : Creates a submenu with NAME,
2123 SUBMENU has the same form as MENU. NAME is also added to the
2124 list of groups of the snippets defined thereafter.
2125
2126 OMIT-ITEMS is a list of snippet uuid's that will always be
2127 omitted from MODE's menu, even if they're manually loaded.
2128
2129 This function does nothing if `yas-use-menu' is nil."
2130 (when yas-use-menu
2131 (let* ((table (yas--table-get-create mode))
2132 (hash (yas--table-uuidhash table)))
2133 (yas--define-menu-1 table
2134 (yas--menu-keymap-get-create mode)
2135 menu
2136 hash)
2137 (dolist (uuid omit-items)
2138 (let ((template (or (gethash uuid hash)
2139 (yas--populate-template (puthash uuid
2140 (yas--make-blank-template)
2141 hash)
2142 :table table
2143 :uuid uuid))))
2144 (setf (yas--template-menu-binding-pair template) (cons nil :none)))))))
2145
2146 (defun yas--define-menu-1 (table menu-keymap menu uuidhash &optional group-list)
2147 "Helper for `yas-define-menu'."
2148 (dolist (e (reverse menu))
2149 (cond ((eq (first e) 'yas-item)
2150 (let ((template (or (gethash (second e) uuidhash)
2151 (yas--populate-template (puthash (second e)
2152 (yas--make-blank-template)
2153 uuidhash)
2154 :table table
2155 :perm-group group-list
2156 :uuid (second e)))))
2157 (define-key menu-keymap (vector (gensym))
2158 (car (yas--template-menu-binding-pair-get-create template :stay)))))
2159 ((eq (first e) 'yas-submenu)
2160 (let ((subkeymap (make-sparse-keymap)))
2161 (define-key menu-keymap (vector (gensym))
2162 `(menu-item ,(second e) ,subkeymap))
2163 (yas--define-menu-1 table
2164 subkeymap
2165 (third e)
2166 uuidhash
2167 (append group-list (list (second e))))))
2168 ((eq (first e) 'yas-separator)
2169 (define-key menu-keymap (vector (gensym))
2170 '(menu-item "----")))
2171 (t
2172 (yas--message 3 "Don't know anything about menu entry %s" (first e))))))
2173 \f
2174 (defun yas--define (mode key template &optional name condition group)
2175 "Define a snippet. Expanding KEY into TEMPLATE.
2176
2177 NAME is a description to this template. Also update the menu if
2178 `yas-use-menu' is t. CONDITION is the condition attached to
2179 this snippet. If you attach a condition to a snippet, then it
2180 will only be expanded when the condition evaluated to non-nil."
2181 (yas-define-snippets mode
2182 (list (list key template name condition group))))
2183
2184 (defun yas-hippie-try-expand (first-time?)
2185 "Integrate with hippie expand.
2186
2187 Just put this function in `hippie-expand-try-functions-list'."
2188 (when yas-minor-mode
2189 (if (not first-time?)
2190 (let ((yas-fallback-behavior 'return-nil))
2191 (yas-expand))
2192 (undo 1)
2193 nil)))
2194
2195
2196 ;;; Apropos condition-cache:
2197 ;;;
2198 ;;;
2199 ;;;
2200 ;;;
2201 (defvar yas--condition-cache-timestamp nil)
2202 (defmacro yas-define-condition-cache (func doc &rest body)
2203 "Define a function FUNC with doc DOC and body BODY, BODY is
2204 executed at most once every snippet expansion attempt, to check
2205 expansion conditions.
2206
2207 It doesn't make any sense to call FUNC programatically."
2208 `(defun ,func () ,(if (and doc
2209 (stringp doc))
2210 (concat doc
2211 "\n\nFor use in snippets' conditions. Within each
2212 snippet-expansion routine like `yas-expand', computes actual
2213 value for the first time then always returns a cached value.")
2214 (setq body (cons doc body))
2215 nil)
2216 (let ((timestamp-and-value (get ',func 'yas--condition-cache)))
2217 (if (equal (car timestamp-and-value) yas--condition-cache-timestamp)
2218 (cdr timestamp-and-value)
2219 (let ((new-value (progn
2220 ,@body
2221 )))
2222 (put ',func 'yas--condition-cache (cons yas--condition-cache-timestamp new-value))
2223 new-value)))))
2224
2225 (defalias 'yas-expand 'yas-expand-from-trigger-key)
2226 (defun yas-expand-from-trigger-key (&optional field)
2227 "Expand a snippet before point.
2228
2229 If no snippet expansion is possible, fall back to the behaviour
2230 defined in `yas-fallback-behavior'.
2231
2232 Optional argument FIELD is for non-interactive use and is an
2233 object satisfying `yas--field-p' to restrict the expansion to."
2234 (interactive)
2235 (setq yas--condition-cache-timestamp (current-time))
2236 (let (templates-and-pos)
2237 (unless (and yas-expand-only-for-last-commands
2238 (not (member last-command yas-expand-only-for-last-commands)))
2239 (setq templates-and-pos (if field
2240 (save-restriction
2241 (narrow-to-region (yas--field-start field)
2242 (yas--field-end field))
2243 (yas--current-key))
2244 (yas--current-key))))
2245 (if (and templates-and-pos
2246 (first templates-and-pos))
2247 (yas--expand-or-prompt-for-template (first templates-and-pos)
2248 (second templates-and-pos)
2249 (third templates-and-pos))
2250 (yas--fallback 'trigger-key))))
2251
2252 (defun yas-expand-from-keymap ()
2253 "Directly expand some snippets, searching `yas--direct-keymaps'.
2254
2255 If expansion fails, execute the previous binding for this key"
2256 (interactive)
2257 (setq yas--condition-cache-timestamp (current-time))
2258 (let* ((yas--prefix current-prefix-arg)
2259 (vec (subseq (this-command-keys-vector) (if current-prefix-arg
2260 universal-argument-num-events
2261 0)))
2262 (templates (mapcan #'(lambda (table)
2263 (yas--fetch table vec))
2264 (yas--get-snippet-tables))))
2265 (if templates
2266 (yas--expand-or-prompt-for-template templates)
2267 (let ((yas-fallback-behavior 'call-other-command))
2268 (yas--fallback)))))
2269
2270 (defun yas--expand-or-prompt-for-template (templates &optional start end)
2271 "Expand one of TEMPLATES from START to END.
2272
2273 Prompt the user if TEMPLATES has more than one element, else
2274 expand immediately. Common gateway for
2275 `yas-expand-from-trigger-key' and `yas-expand-from-keymap'."
2276 (let ((yas--current-template (or (and (rest templates) ;; more than one
2277 (yas--prompt-for-template (mapcar #'cdr templates)))
2278 (cdar templates))))
2279 (when yas--current-template
2280 (yas-expand-snippet (yas--template-content yas--current-template)
2281 start
2282 end
2283 (yas--template-expand-env yas--current-template)))))
2284
2285 ;; Apropos the trigger key and the fallback binding:
2286 ;;
2287 ;; When `yas-minor-mode-map' binds <tab>, that correctly overrides
2288 ;; org-mode's <tab>, for example and searching for fallbacks correctly
2289 ;; returns `org-cycle'. However, most other modes bind "TAB". TODO,
2290 ;; improve this explanation.
2291 ;;
2292 (defun yas--fallback (&optional from-trigger-key-p)
2293 "Fallback after expansion has failed.
2294
2295 Common gateway for `yas-expand-from-trigger-key' and
2296 `yas-expand-from-keymap'."
2297 (cond ((eq yas-fallback-behavior 'return-nil)
2298 ;; return nil
2299 nil)
2300 ((eq yas-fallback-behavior 'call-other-command)
2301 (let* ((beyond-yasnippet (yas--keybinding-beyond-yasnippet)))
2302 (yas--message 4 "Falling back to %s" beyond-yasnippet)
2303 (assert (or (null beyond-yasnippet) (commandp beyond-yasnippet)))
2304 (setq this-original-command beyond-yasnippet)
2305 (call-interactively beyond-yasnippet)))
2306 ((and (listp yas-fallback-behavior)
2307 (cdr yas-fallback-behavior)
2308 (eq 'apply (car yas-fallback-behavior)))
2309 (if (cddr yas-fallback-behavior)
2310 (apply (cadr yas-fallback-behavior)
2311 (cddr yas-fallback-behavior))
2312 (when (commandp (cadr yas-fallback-behavior))
2313 (setq this-command (cadr yas-fallback-behavior))
2314 (call-interactively (cadr yas-fallback-behavior)))))
2315 (t
2316 ;; also return nil if all the other fallbacks have failed
2317 nil)))
2318
2319 (defun yas--keybinding-beyond-yasnippet ()
2320 "Returns the "
2321 (let* ((yas-minor-mode nil)
2322 (yas--direct-keymaps nil)
2323 (keys (this-single-command-keys)))
2324 (or (key-binding keys t)
2325 (key-binding (yas--fallback-translate-input keys) t))))
2326
2327 (defun yas--fallback-translate-input (keys)
2328 "Emulate `read-key-sequence', at least what I think it does.
2329
2330 Keys should be an untranslated key vector. Returns a translated
2331 vector of keys. FIXME not thoroughly tested"
2332 (let ((retval [])
2333 (i 0))
2334 (while (< i (length keys))
2335 (let ((j i)
2336 (translated local-function-key-map))
2337 (while (and (< j (length keys))
2338 translated
2339 (keymapp translated))
2340 (setq translated (cdr (assoc (aref keys j) (remove 'keymap translated)))
2341 j (1+ j)))
2342 (setq retval (vconcat retval (cond ((symbolp translated)
2343 `[,translated])
2344 ((vectorp translated)
2345 translated)
2346 (t
2347 (substring keys i j)))))
2348 (setq i j)))
2349 retval))
2350
2351 \f
2352 ;;; Utils for snippet development:
2353
2354 (defun yas--all-templates (tables)
2355 "Get `yas--template' objects in TABLES, applicable for buffer and point.
2356
2357 Honours `yas-choose-tables-first', `yas-choose-keys-first' and
2358 `yas-buffer-local-condition'"
2359 (when yas-choose-tables-first
2360 (setq tables (list (yas--prompt-for-table tables))))
2361 (mapcar #'cdr
2362 (if yas-choose-keys-first
2363 (let ((key (yas--prompt-for-keys
2364 (mapcan #'yas--table-all-keys tables))))
2365 (when key
2366 (mapcan #'(lambda (table)
2367 (yas--fetch table key))
2368 tables)))
2369 (remove-duplicates (mapcan #'yas--table-templates tables)
2370 :test #'equal))))
2371
2372 (defun yas-insert-snippet (&optional no-condition)
2373 "Choose a snippet to expand, pop-up a list of choices according
2374 to `yas--prompt-function'.
2375
2376 With prefix argument NO-CONDITION, bypass filtering of snippets
2377 by condition."
2378 (interactive "P")
2379 (setq yas--condition-cache-timestamp (current-time))
2380 (let* ((yas-buffer-local-condition (or (and no-condition
2381 'always)
2382 yas-buffer-local-condition))
2383 (templates (yas--all-templates (yas--get-snippet-tables)))
2384 (yas--current-template (and templates
2385 (or (and (rest templates) ;; more than one template for same key
2386 (yas--prompt-for-template templates))
2387 (car templates))))
2388 (where (if (region-active-p)
2389 (cons (region-beginning) (region-end))
2390 (cons (point) (point)))))
2391 (if yas--current-template
2392 (yas-expand-snippet (yas--template-content yas--current-template)
2393 (car where)
2394 (cdr where)
2395 (yas--template-expand-env yas--current-template))
2396 (yas--message 3 "No snippets can be inserted here!"))))
2397
2398 (defun yas-visit-snippet-file ()
2399 "Choose a snippet to edit, selection like `yas-insert-snippet'.
2400
2401 Only success if selected snippet was loaded from a file. Put the
2402 visited file in `snippet-mode'."
2403 (interactive)
2404 (let* ((yas-buffer-local-condition 'always)
2405 (templates (yas--all-templates (yas--get-snippet-tables)))
2406 (yas-prompt-functions '(yas-ido-prompt yas-completing-prompt))
2407 (template (and templates
2408 (or (yas--prompt-for-template templates
2409 "Choose a snippet template to edit: ")
2410 (car templates)))))
2411
2412 (if template
2413 (yas--visit-snippet-file-1 template)
2414 (message "No snippets tables active!"))))
2415
2416 (defun yas--visit-snippet-file-1 (template)
2417 "Helper for `yas-visit-snippet-file'."
2418 (let ((file (yas--template-file template)))
2419 (cond ((and file (file-readable-p file))
2420 (find-file-other-window file)
2421 (snippet-mode)
2422 (set (make-local-variable 'yas--editing-template) template))
2423 (file
2424 (message "Original file %s no longer exists!" file))
2425 (t
2426 (switch-to-buffer (format "*%s*"(yas--template-name template)))
2427 (let ((type 'snippet))
2428 (when (listp (yas--template-content template))
2429 (insert (format "# type: command\n"))
2430 (setq type 'command))
2431 (insert (format "# key: %s\n" (yas--template-key template)))
2432 (insert (format "# name: %s\n" (yas--template-name template)))
2433 (when (yas--template-keybinding template)
2434 (insert (format "# binding: %s\n" (yas--template-keybinding template))))
2435 (when (yas--template-expand-env template)
2436 (insert (format "# expand-env: %s\n" (yas--template-expand-env template))))
2437 (when (yas--template-condition template)
2438 (insert (format "# condition: %s\n" (yas--template-condition template))))
2439 (insert "# --\n")
2440 (insert (if (eq type 'command)
2441 (pp-to-string (yas--template-content template))
2442 (yas--template-content template))))
2443 (snippet-mode)
2444 (set (make-local-variable 'yas--editing-template) template)))))
2445
2446 (defun yas--guess-snippet-directories-1 (table)
2447 "Guesses possible snippet subdirectories for TABLE."
2448 (cons (yas--table-name table)
2449 (mapcan #'(lambda (parent)
2450 (yas--guess-snippet-directories-1
2451 parent))
2452 (yas--table-parents table))))
2453
2454 (defun yas--guess-snippet-directories (&optional table)
2455 "Try to guess suitable directories based on the current active
2456 tables (or optional TABLE).
2457
2458 Returns a list of elements (TABLE . DIRS) where TABLE is a
2459 `yas--table' object and DIRS is a list of all possible directories
2460 where snippets of table might exist."
2461 (let ((main-dir (replace-regexp-in-string
2462 "/+$" ""
2463 (or (first (or (yas-snippet-dirs)
2464 (setq yas-snippet-dirs '("~/.emacs.d/snippets")))))))
2465 (tables (or (and table
2466 (list table))
2467 (yas--get-snippet-tables))))
2468 ;; HACK! the snippet table created here is actually registered!
2469 ;;
2470 (unless (or table (gethash major-mode yas--tables))
2471 (push (yas--table-get-create major-mode)
2472 tables))
2473
2474 (mapcar #'(lambda (table)
2475 (cons table
2476 (mapcar #'(lambda (subdir)
2477 (concat main-dir "/" subdir))
2478 (yas--guess-snippet-directories-1 table))))
2479 tables)))
2480
2481 (defun yas--make-directory-maybe (table-and-dirs &optional main-table-string)
2482 "Returns a dir inside TABLE-AND-DIRS, prompts for creation if none exists."
2483 (or (some #'(lambda (dir) (when (file-directory-p dir) dir)) (cdr table-and-dirs))
2484 (let ((candidate (first (cdr table-and-dirs))))
2485 (unless (file-writable-p (file-name-directory candidate))
2486 (error (yas--format "%s is not writable." candidate)))
2487 (if (y-or-n-p (format "Guessed directory (%s) for%s%s table \"%s\" does not exist! Create? "
2488 candidate
2489 (if (gethash (yas--table-mode (car table-and-dirs))
2490 yas--tables)
2491 ""
2492 " brand new")
2493 (or main-table-string
2494 "")
2495 (yas--table-name (car table-and-dirs))))
2496 (progn
2497 (make-directory candidate 'also-make-parents)
2498 ;; create the .yas-parents file here...
2499 candidate)))))
2500
2501 (defun yas-new-snippet (&optional no-template)
2502 "Pops a new buffer for writing a snippet.
2503
2504 Expands a snippet-writing snippet, unless the optional prefix arg
2505 NO-TEMPLATE is non-nil."
2506 (interactive "P")
2507 (let ((guessed-directories (yas--guess-snippet-directories)))
2508
2509 (switch-to-buffer "*new snippet*")
2510 (erase-buffer)
2511 (kill-all-local-variables)
2512 (snippet-mode)
2513 (yas-minor-mode 1)
2514 (set (make-local-variable 'yas--guessed-modes) (mapcar #'(lambda (d)
2515 (yas--table-mode (car d)))
2516 guessed-directories))
2517 (unless no-template (yas-expand-snippet "\
2518 # -*- mode: snippet -*-
2519 # name: $1
2520 # key: ${2:${1:$(replace-regexp-in-string \"\\\\\\\\(\\\\\\\\w+\\\\\\\\).*\" \"\\\\\\\\1\" yas-text)}}${3:
2521 # binding: ${4:direct-keybinding}}${5:
2522 # expand-env: ((${6:some-var} ${7:some-value}))}${8:
2523 # type: command}
2524 # --
2525 $0"))))
2526
2527 (defun yas--compute-major-mode-and-parents (file)
2528 "Given FILE, find the nearest snippet directory for a given mode.
2529
2530 Returns a list (MODE-SYM PARENTS), the mode's symbol and a list
2531 representing one or more of the mode's parents.
2532
2533 Note that MODE-SYM need not be the symbol of a real major mode,
2534 neither do the elements of PARENTS."
2535 (let* ((file-dir (and file
2536 (directory-file-name (or (some #'(lambda (special)
2537 (locate-dominating-file file special))
2538 '(".yas-setup.el"
2539 ".yas-make-groups"
2540 ".yas-parents"))
2541 (directory-file-name (file-name-directory file))))))
2542 (parents-file-name (concat file-dir "/.yas-parents"))
2543 (major-mode-name (and file-dir
2544 (file-name-nondirectory file-dir)))
2545 (major-mode-sym (or (and major-mode-name
2546 (intern major-mode-name))))
2547 (parents (when (file-readable-p parents-file-name)
2548 (mapcar #'intern
2549 (split-string
2550 (with-temp-buffer
2551 (insert-file-contents parents-file-name)
2552 (buffer-substring-no-properties (point-min)
2553 (point-max))))))))
2554 (when major-mode-sym
2555 (cons major-mode-sym (remove major-mode-sym parents)))))
2556
2557 (defvar yas--editing-template nil
2558 "Supporting variable for `yas-load-snippet-buffer' and `yas--visit-snippet'.")
2559
2560 (defvar yas--current-template nil
2561 "Holds the current template being expanded into a snippet.")
2562
2563 (defvar yas--guessed-modes nil
2564 "List of guessed modes supporting `yas-load-snippet-buffer'.")
2565
2566 (defun yas--read-table ()
2567 "Ask user for a snippet table, help with some guessing."
2568 (let ((prompt (if (and (featurep 'ido)
2569 ido-mode)
2570 'ido-completing-read 'completing-read)))
2571 (unless yas--guessed-modes
2572 (set (make-local-variable 'yas--guessed-modes)
2573 (or (yas--compute-major-mode-and-parents buffer-file-name))))
2574 (intern
2575 (funcall prompt (format "Choose or enter a table (yas guesses %s): "
2576 (if yas--guessed-modes
2577 (first yas--guessed-modes)
2578 "nothing"))
2579 (mapcar #'symbol-name yas--guessed-modes)
2580 nil
2581 nil
2582 nil
2583 nil
2584 (if (first yas--guessed-modes)
2585 (symbol-name (first yas--guessed-modes)))))))
2586
2587 (defun yas-load-snippet-buffer (table &optional interactive)
2588 "Parse and load current buffer's snippet definition into TABLE.
2589
2590 TABLE is a symbol naming a passed to `yas--table-get-create'.
2591
2592 When called interactively, prompt for the table name and
2593 whether (and where) to save the snippet, then quit the window."
2594 (interactive (list (yas--read-table) t))
2595 (cond
2596 ;; We have `yas--editing-template', this buffer's content comes from a
2597 ;; template which is already loaded and neatly positioned,...
2598 ;;
2599 (yas--editing-template
2600 (yas--define-snippets-1 (yas--parse-template (yas--template-file yas--editing-template))
2601 (yas--template-table yas--editing-template)))
2602 ;; Try to use `yas--guessed-modes'. If we don't have that use the
2603 ;; value from `yas--compute-major-mode-and-parents'
2604 ;;
2605 (t
2606 (unless yas--guessed-modes
2607 (set (make-local-variable 'yas--guessed-modes) (or (yas--compute-major-mode-and-parents buffer-file-name))))
2608 (let* ((table (yas--table-get-create table)))
2609 (set (make-local-variable 'yas--editing-template)
2610 (yas--define-snippets-1 (yas--parse-template buffer-file-name)
2611 table)))))
2612
2613 (when (and interactive
2614 (or
2615 ;; Only offer to save this if it looks like a library or new
2616 ;; snippet (loaded from elisp, from a dir in `yas-snippet-dirs'
2617 ;; which is not the first, or from an unwritable file)
2618 ;;
2619 (not (yas--template-file yas--editing-template))
2620 (not (file-writable-p (yas--template-file yas--editing-template)))
2621 (and (listp yas-snippet-dirs)
2622 (second yas-snippet-dirs)
2623 (not (string-match (expand-file-name (first yas-snippet-dirs))
2624 (yas--template-file yas--editing-template)))))
2625 (y-or-n-p (yas--format "Looks like a library or new snippet. Save to new file? ")))
2626 (let* ((option (first (yas--guess-snippet-directories (yas--template-table yas--editing-template))))
2627 (chosen (and option
2628 (yas--make-directory-maybe option))))
2629 (when chosen
2630 (let ((default-file-name (or (and (yas--template-file yas--editing-template)
2631 (file-name-nondirectory (yas--template-file yas--editing-template)))
2632 (yas--template-name yas--editing-template))))
2633 (write-file (concat chosen "/"
2634 (read-from-minibuffer (format "File name to create in %s? " chosen)
2635 default-file-name)))
2636 (setf (yas--template-file yas--editing-template) buffer-file-name)))))
2637 (when interactive
2638 (yas--message 3 "Snippet \"%s\" loaded for %s."
2639 (yas--template-name yas--editing-template)
2640 (yas--table-name (yas--template-table yas--editing-template)))
2641 (quit-window interactive)))
2642
2643 (defun yas-tryout-snippet (&optional debug)
2644 "Test current buffer's snippet template in other buffer."
2645 (interactive "P")
2646 (let* ((major-mode-and-parent (yas--compute-major-mode-and-parents buffer-file-name))
2647 (parsed (yas--parse-template))
2648 (test-mode (or (and (car major-mode-and-parent)
2649 (fboundp (car major-mode-and-parent))
2650 (car major-mode-and-parent))
2651 (first yas--guessed-modes)
2652 (intern (read-from-minibuffer (yas--format "Please input a mode: ")))))
2653 (yas--current-template
2654 (and parsed
2655 (fboundp test-mode)
2656 (yas--populate-template (yas--make-blank-template)
2657 :table nil ;; no tables for ephemeral snippets
2658 :key (first parsed)
2659 :content (second parsed)
2660 :name (third parsed)
2661 :expand-env (sixth parsed)))))
2662 (cond (yas--current-template
2663 (let ((buffer-name (format "*testing snippet: %s*" (yas--template-name yas--current-template))))
2664 (kill-buffer (get-buffer-create buffer-name))
2665 (switch-to-buffer (get-buffer-create buffer-name))
2666 (setq buffer-undo-list nil)
2667 (condition-case nil (funcall test-mode) (error nil))
2668 (yas-minor-mode 1)
2669 (setq buffer-read-only nil)
2670 (yas-expand-snippet (yas--template-content yas--current-template)
2671 (point-min)
2672 (point-max)
2673 (yas--template-expand-env yas--current-template))
2674 (when (and debug
2675 (require 'yasnippet-debug nil t))
2676 (add-hook 'post-command-hook 'yas-debug-snippet-vars nil t))))
2677 (t
2678 (yas--message 3 "Cannot test snippet for unknown major mode")))))
2679
2680 (defun yas-active-keys ()
2681 "Return all active trigger keys for current buffer and point."
2682 (remove-duplicates
2683 (remove-if-not #'stringp (mapcan #'yas--table-all-keys (yas--get-snippet-tables)))
2684 :test #'string=))
2685
2686 (defun yas--template-fine-group (template)
2687 (car (last (or (yas--template-group template)
2688 (yas--template-perm-group template)))))
2689
2690 (defun yas-describe-tables (&optional choose)
2691 "Display snippets for each table."
2692 (interactive "P")
2693 (let* ((by-name-hash (and choose
2694 (y-or-n-p "Show by namehash? ")))
2695 (buffer (get-buffer-create "*YASnippet tables*"))
2696 (active-tables (yas--get-snippet-tables))
2697 (remain-tables (let ((all))
2698 (maphash #'(lambda (k v)
2699 (unless (find v active-tables)
2700 (push v all)))
2701 yas--tables)
2702 all))
2703 (table-lists (list active-tables remain-tables))
2704 (original-buffer (current-buffer))
2705 (continue t)
2706 (yas--condition-cache-timestamp (current-time)))
2707 (with-current-buffer buffer
2708 (setq buffer-read-only nil)
2709 (erase-buffer)
2710 (cond ((not by-name-hash)
2711 (insert "YASnippet tables: \n")
2712 (while (and table-lists
2713 continue)
2714 (dolist (table (car table-lists))
2715 (yas--describe-pretty-table table original-buffer))
2716 (setq table-lists (cdr table-lists))
2717 (when table-lists
2718 (yas--create-snippet-xrefs)
2719 (display-buffer buffer)
2720 (setq continue (and choose (y-or-n-p "Show also non-active tables? ")))))
2721 (yas--create-snippet-xrefs)
2722 (help-mode)
2723 (goto-char 1))
2724 (t
2725 (insert "\n\nYASnippet tables by NAMEHASH: \n")
2726 (dolist (table (append active-tables remain-tables))
2727 (insert (format "\nSnippet table `%s':\n\n" (yas--table-name table)))
2728 (let ((keys))
2729 (maphash #'(lambda (k v)
2730 (push k keys))
2731 (yas--table-hash table))
2732 (dolist (key keys)
2733 (insert (format " key %s maps snippets: %s\n" key
2734 (let ((names))
2735 (maphash #'(lambda (k v)
2736 (push k names))
2737 (gethash key (yas--table-hash table)))
2738 names))))))))
2739 (goto-char 1)
2740 (setq buffer-read-only t))
2741 (display-buffer buffer)))
2742
2743 (defun yas--describe-pretty-table (table &optional original-buffer)
2744 (insert (format "\nSnippet table `%s'"
2745 (yas--table-name table)))
2746 (if (yas--table-parents table)
2747 (insert (format " parents: %s\n"
2748 (mapcar #'yas--table-name
2749 (yas--table-parents table))))
2750 (insert "\n"))
2751 (insert (make-string 100 ?-) "\n")
2752 (insert "group state name key binding\n")
2753 (let ((groups-hash (make-hash-table :test #'equal)))
2754 (maphash #'(lambda (k v)
2755 (let ((group (or (yas--template-fine-group v)
2756 "(top level)")))
2757 (when (yas--template-name v)
2758 (puthash group
2759 (cons v (gethash group groups-hash))
2760 groups-hash))))
2761 (yas--table-uuidhash table))
2762 (maphash
2763 #'(lambda (group templates)
2764 (setq group (truncate-string-to-width group 25 0 ? "..."))
2765 (insert (make-string 100 ?-) "\n")
2766 (dolist (p templates)
2767 (let ((name (truncate-string-to-width (propertize (format "\\\\snippet `%s'" (yas--template-name p))
2768 'yasnippet p)
2769 50 0 ? "..."))
2770 (group (prog1 group
2771 (setq group (make-string (length group) ? ))))
2772 (condition-string (let ((condition (yas--template-condition p)))
2773 (if (and condition
2774 original-buffer)
2775 (with-current-buffer original-buffer
2776 (if (yas--eval-condition condition)
2777 "(y)"
2778 "(s)"))
2779 "(a)"))))
2780 (insert group " ")
2781 (insert condition-string " ")
2782 (insert name
2783 (if (string-match "\\.\\.\\.$" name)
2784 "'"
2785 " ")
2786 " ")
2787 (insert (truncate-string-to-width (or (yas--template-key p) "")
2788 15 0 ? "...") " ")
2789 (insert (truncate-string-to-width (key-description (yas--template-keybinding p))
2790 15 0 ? "...") " ")
2791 (insert "\n"))))
2792 groups-hash)))
2793
2794
2795 \f
2796 ;;; User convenience functions, for using in snippet definitions
2797
2798 (defvar yas-modified-p nil
2799 "Non-nil if field has been modified by user or transformation.")
2800
2801 (defvar yas-moving-away-p nil
2802 "Non-nil if user is about to exit field.")
2803
2804 (defvar yas-text nil
2805 "Contains current field text.")
2806
2807 (defun yas-substr (str pattern &optional subexp)
2808 "Search PATTERN in STR and return SUBEXPth match.
2809
2810 If found, the content of subexp group SUBEXP (default 0) is
2811 returned, or else the original STR will be returned."
2812 (let ((grp (or subexp 0)))
2813 (save-match-data
2814 (if (string-match pattern str)
2815 (match-string-no-properties grp str)
2816 str))))
2817
2818 (defun yas-choose-value (&rest possibilities)
2819 "Prompt for a string in POSSIBILITIES and return it.
2820
2821 The last element of POSSIBILITIES may be a list of strings."
2822 (unless (or yas-moving-away-p
2823 yas-modified-p)
2824 (setq possibilities (nreverse possibilities))
2825 (setq possibilities (if (listp (car possibilities))
2826 (append (reverse (car possibilities)) (rest possibilities))
2827 possibilities))
2828 (some #'(lambda (fn)
2829 (funcall fn "Choose: " possibilities))
2830 yas-prompt-functions)))
2831
2832 (defun yas-key-to-value (alist)
2833 (unless (or yas-moving-away-p
2834 yas-modified-p)
2835 (let ((key (read-key-sequence "")))
2836 (when (stringp key)
2837 (or (cdr (find key alist :key #'car :test #'string=))
2838 key)))))
2839
2840 (defun yas-throw (text)
2841 "Throw a yas--exception with TEXT as the reason."
2842 (throw 'yas--exception (cons 'yas--exception text)))
2843
2844 (defun yas-verify-value (possibilities)
2845 "Verify that the current field value is in POSSIBILITIES.
2846
2847 Otherwise throw exception."
2848 (when (and yas-moving-away-p (notany #'(lambda (pos) (string= pos yas-text)) possibilities))
2849 (yas-throw (yas--format "Field only allows %s" possibilities))))
2850
2851 (defun yas-field-value (number)
2852 "Get the string for field with NUMBER.
2853
2854 Use this in primary and mirror transformations to tget."
2855 (let* ((snippet (car (yas--snippets-at-point)))
2856 (field (and snippet
2857 (yas--snippet-find-field snippet number))))
2858 (when field
2859 (yas--field-text-for-display field))))
2860
2861 (defun yas-text ()
2862 "Return `yas-text' if that exists and is non-empty, else nil."
2863 (if (and yas-text
2864 (not (string= "" yas-text)))
2865 yas-text))
2866
2867 (defun yas-selected-text ()
2868 "Return `yas-selected-text' if that exists and is non-empty, else nil."
2869 (if (and yas-selected-text
2870 (not (string= "" yas-selected-text)))
2871 yas-selected-text))
2872
2873 (defun yas--get-field-once (number &optional transform-fn)
2874 (unless yas-modified-p
2875 (if transform-fn
2876 (funcall transform-fn (yas-field-value number))
2877 (yas-field-value number))))
2878
2879 (defun yas-default-from-field (number)
2880 (unless yas-modified-p
2881 (yas-field-value number)))
2882
2883 (defun yas-inside-string ()
2884 "Return non-nil if the point is inside a string according to font-lock."
2885 (equal 'font-lock-string-face (get-char-property (1- (point)) 'face)))
2886
2887 (defun yas-unimplemented (&optional missing-feature)
2888 (if yas--current-template
2889 (if (y-or-n-p (format "This snippet is unimplemented (missing %s) Visit the snippet definition? "
2890 (or missing-feature
2891 "something")))
2892 (yas--visit-snippet-file-1 yas--current-template))
2893 (message "No implementation. Missing %s" (or missing-feature "something"))))
2894
2895 \f
2896 ;;; Snippet expansion and field management
2897
2898 (defvar yas--active-field-overlay nil
2899 "Overlays the currently active field.")
2900
2901 (defvar yas--field-protection-overlays nil
2902 "Two overlays protect the current active field.")
2903
2904 (defconst yas--prefix nil
2905 "A prefix argument for expansion direct from keybindings.")
2906
2907 (defvar yas-selected-text nil
2908 "The selected region deleted on the last snippet expansion.")
2909
2910 (defvar yas--start-column nil
2911 "The column where the snippet expansion started.")
2912
2913 (make-variable-buffer-local 'yas--active-field-overlay)
2914 (make-variable-buffer-local 'yas--field-protection-overlays)
2915 (put 'yas--active-field-overlay 'permanent-local t)
2916 (put 'yas--field-protection-overlays 'permanent-local t)
2917
2918 (defstruct (yas--snippet (:constructor yas--make-snippet ()))
2919 "A snippet.
2920
2921 ..."
2922 (fields '())
2923 (exit nil)
2924 (id (yas--snippet-next-id) :read-only t)
2925 (control-overlay nil)
2926 active-field
2927 ;; stacked expansion: the `previous-active-field' slot saves the
2928 ;; active field where the child expansion took place
2929 previous-active-field
2930 force-exit)
2931
2932 (defstruct (yas--field (:constructor yas--make-field (number start end parent-field)))
2933 "A field.
2934
2935 NUMBER is the field number.
2936 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2937 PARENT-FIELD is a `yas--field' this field is nested under, or nil.
2938 MIRRORS is a list of `yas--mirror's
2939 TRANSFORM is a lisp form.
2940 MODIFIED-P is a boolean set to true once user inputs text.
2941 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'.
2942 "
2943 number
2944 start end
2945 parent-field
2946 (mirrors '())
2947 (transform nil)
2948 (modified-p nil)
2949 next)
2950
2951
2952 (defstruct (yas--mirror (:constructor yas--make-mirror (start end transform)))
2953 "A mirror.
2954
2955 START and END are mostly buffer markers, but see \"apropos markers-to-points\".
2956 TRANSFORM is a lisp form.
2957 PARENT-FIELD is a `yas--field' this mirror is nested under, or nil.
2958 NEXT is another `yas--field' or `yas--mirror' or `yas--exit'
2959 DEPTH is a count of how many nested mirrors can affect this mirror"
2960 start end
2961 (transform nil)
2962 parent-field
2963 next
2964 depth)
2965
2966 (defstruct (yas--exit (:constructor yas--make-exit (marker)))
2967 marker
2968 next)
2969
2970 (defun yas--apply-transform (field-or-mirror field &optional empty-on-nil-p)
2971 "Calculate transformed string for FIELD-OR-MIRROR from FIELD.
2972
2973 If there is no transform for ht field, return nil.
2974
2975 If there is a transform but it returns nil, return the empty
2976 string iff EMPTY-ON-NIL-P is true."
2977 (let* ((yas-text (yas--field-text-for-display field))
2978 (text yas-text)
2979 (yas-modified-p (yas--field-modified-p field))
2980 (yas-moving-away-p nil)
2981 (transform (if (yas--mirror-p field-or-mirror)
2982 (yas--mirror-transform field-or-mirror)
2983 (yas--field-transform field-or-mirror)))
2984 (start-point (if (yas--mirror-p field-or-mirror)
2985 (yas--mirror-start field-or-mirror)
2986 (yas--field-start field-or-mirror)))
2987 (transformed (and transform
2988 (save-excursion
2989 (goto-char start-point)
2990 (let ((ret (yas--eval-lisp transform)))
2991 (or ret (and empty-on-nil-p "")))))))
2992 transformed))
2993
2994 (defsubst yas--replace-all (from to &optional text)
2995 "Replace all occurrences from FROM to TO.
2996
2997 With optional string TEXT do it in that string."
2998 (if text
2999 (replace-regexp-in-string (regexp-quote from) to text t t)
3000 (goto-char (point-min))
3001 (while (search-forward from nil t)
3002 (replace-match to t t text))))
3003
3004 (defun yas--snippet-find-field (snippet number)
3005 (find-if #'(lambda (field)
3006 (eq number (yas--field-number field)))
3007 (yas--snippet-fields snippet)))
3008
3009 (defun yas--snippet-sort-fields (snippet)
3010 "Sort the fields of SNIPPET in navigation order."
3011 (setf (yas--snippet-fields snippet)
3012 (sort (yas--snippet-fields snippet)
3013 #'yas--snippet-field-compare)))
3014
3015 (defun yas--snippet-field-compare (field1 field2)
3016 "Compare FIELD1 and FIELD2.
3017
3018 The field with a number is sorted first. If they both have a
3019 number, compare through the number. If neither have, compare
3020 through the field's start point"
3021 (let ((n1 (yas--field-number field1))
3022 (n2 (yas--field-number field2)))
3023 (if n1
3024 (if n2
3025 (or (zerop n2) (and (not (zerop n1))
3026 (< n1 n2)))
3027 (not (zerop n1)))
3028 (if n2
3029 (zerop n2)
3030 (< (yas--field-start field1)
3031 (yas--field-start field2))))))
3032
3033 (defun yas--field-probably-deleted-p (snippet field)
3034 "Guess if SNIPPET's FIELD should be skipped."
3035 (and
3036 ;; field must be zero length
3037 ;;
3038 (zerop (- (yas--field-start field) (yas--field-end field)))
3039 ;; skip if:
3040 (or
3041 ;; 1) is a nested field and it's been modified
3042 ;;
3043 (and (yas--field-parent-field field)
3044 (yas--field-modified-p field))
3045 ;; 2) ends just before the snippet end
3046 ;;
3047 (and (eq field (car (last (yas--snippet-fields snippet))))
3048 (= (yas--field-start field) (overlay-end (yas--snippet-control-overlay snippet)))))
3049 ;; the field numbered 0, just before the exit marker, should
3050 ;; never be skipped
3051 ;;
3052 (not (zerop (yas--field-number field)))))
3053
3054 (defun yas--snippets-at-point (&optional all-snippets)
3055 "Return a sorted list of snippets at point.
3056
3057 The most recently-inserted snippets are returned first."
3058 (sort
3059 (remove nil (remove-duplicates (mapcar #'(lambda (ov)
3060 (overlay-get ov 'yas--snippet))
3061 (if all-snippets
3062 (overlays-in (point-min) (point-max))
3063 (nconc (overlays-at (point)) (overlays-at (1- (point))))))))
3064 #'(lambda (s1 s2)
3065 (<= (yas--snippet-id s2) (yas--snippet-id s1)))))
3066
3067 (defun yas-next-field-or-maybe-expand ()
3068 "Try to expand a snippet at a key before point.
3069
3070 Otherwise delegate to `yas-next-field'."
3071 (interactive)
3072 (if yas-triggers-in-field
3073 (let ((yas-fallback-behavior 'return-nil)
3074 (active-field (overlay-get yas--active-field-overlay 'yas--field)))
3075 (when active-field
3076 (unless (yas-expand-from-trigger-key active-field)
3077 (yas-next-field))))
3078 (yas-next-field)))
3079
3080 (defun yas-next-field (&optional arg)
3081 "Navigate to the ARGth next field.
3082
3083 If there's none, exit the snippet."
3084 (interactive)
3085 (let* ((arg (or arg
3086 1))
3087 (snippet (first (yas--snippets-at-point)))
3088 (active-field (overlay-get yas--active-field-overlay 'yas--field))
3089 (live-fields (remove-if #'(lambda (field)
3090 (and (not (eq field active-field))
3091 (yas--field-probably-deleted-p snippet field)))
3092 (yas--snippet-fields snippet)))
3093 (active-field-pos (position active-field live-fields))
3094 (target-pos (and active-field-pos (+ arg active-field-pos)))
3095 (target-field (and target-pos (nth target-pos live-fields))))
3096 ;; First check if we're moving out of a field with a transform
3097 ;;
3098 (when (and active-field
3099 (yas--field-transform active-field))
3100 (let* ((yas-moving-away-p t)
3101 (yas-text (yas--field-text-for-display active-field))
3102 (text yas-text)
3103 (yas-modified-p (yas--field-modified-p active-field)))
3104 ;; primary field transform: exit call to field-transform
3105 (yas--eval-lisp (yas--field-transform active-field))))
3106 ;; Now actually move...
3107 (cond ((and target-pos (>= target-pos (length live-fields)))
3108 (yas-exit-snippet snippet))
3109 (target-field
3110 (yas--move-to-field snippet target-field))
3111 (t
3112 nil))))
3113
3114 (defun yas--place-overlays (snippet field)
3115 "Correctly place overlays for SNIPPET's FIELD."
3116 (yas--make-move-field-protection-overlays snippet field)
3117 (yas--make-move-active-field-overlay snippet field))
3118
3119 (defun yas--move-to-field (snippet field)
3120 "Update SNIPPET to move to field FIELD.
3121
3122 Also create some protection overlays"
3123 (goto-char (yas--field-start field))
3124 (yas--place-overlays snippet field)
3125 (overlay-put yas--active-field-overlay 'yas--field field)
3126 (let ((number (yas--field-number field)))
3127 ;; check for the special ${0: ...} field
3128 (if (and number (zerop number))
3129 (progn
3130 (set-mark (yas--field-end field))
3131 (setf (yas--snippet-force-exit snippet)
3132 (or (yas--field-transform field)
3133 t)))
3134 ;; make this field active
3135 (setf (yas--snippet-active-field snippet) field)
3136 ;; primary field transform: first call to snippet transform
3137 (unless (yas--field-modified-p field)
3138 (if (yas--field-update-display field snippet)
3139 (yas--update-mirrors snippet)
3140 (setf (yas--field-modified-p field) nil))))))
3141
3142 (defun yas-prev-field ()
3143 "Navigate to prev field. If there's none, exit the snippet."
3144 (interactive)
3145 (yas-next-field -1))
3146
3147 (defun yas-abort-snippet (&optional snippet)
3148 (interactive)
3149 (let ((snippet (or snippet
3150 (car (yas--snippets-at-point)))))
3151 (when snippet
3152 (setf (yas--snippet-force-exit snippet) t))))
3153
3154 (defun yas-exit-snippet (snippet)
3155 "Goto exit-marker of SNIPPET."
3156 (interactive (list (first (yas--snippets-at-point))))
3157 (when snippet
3158 (setf (yas--snippet-force-exit snippet) t)
3159 (goto-char (if (yas--snippet-exit snippet)
3160 (yas--exit-marker (yas--snippet-exit snippet))
3161 (overlay-end (yas--snippet-control-overlay snippet))))))
3162
3163 (defun yas-exit-all-snippets ()
3164 "Exit all snippets."
3165 (interactive)
3166 (mapc #'(lambda (snippet)
3167 (yas-exit-snippet snippet)
3168 (yas--check-commit-snippet))
3169 (yas--snippets-at-point 'all-snippets)))
3170
3171 \f
3172 ;;; Some low level snippet-routines:
3173
3174 (defmacro yas--inhibit-overlay-hooks (&rest body)
3175 "Run BODY with `yas--inhibit-overlay-hooks' set to t."
3176 (declare (indent 0))
3177 `(let ((yas--inhibit-overlay-hooks t))
3178 (progn ,@body)))
3179
3180 (defvar yas-snippet-beg nil "Beginning position of the last snippet committed.")
3181 (defvar yas-snippet-end nil "End position of the last snippet committed.")
3182
3183 (defun yas--commit-snippet (snippet)
3184 "Commit SNIPPET, but leave point as it is.
3185
3186 This renders the snippet as ordinary text."
3187
3188 (let ((control-overlay (yas--snippet-control-overlay snippet)))
3189 ;;
3190 ;; Save the end of the moribund snippet in case we need to revive it
3191 ;; its original expansion.
3192 ;;
3193 (when (and control-overlay
3194 (overlay-buffer control-overlay))
3195 (setq yas-snippet-beg (overlay-start control-overlay))
3196 (setq yas-snippet-end (overlay-end control-overlay))
3197 (delete-overlay control-overlay))
3198
3199 (yas--inhibit-overlay-hooks
3200 (when yas--active-field-overlay
3201 (delete-overlay yas--active-field-overlay))
3202 (when yas--field-protection-overlays
3203 (mapc #'delete-overlay yas--field-protection-overlays)))
3204
3205 ;; stacked expansion: if the original expansion took place from a
3206 ;; field, make sure we advance it here at least to
3207 ;; `yas-snippet-end'...
3208 ;;
3209 (let ((previous-field (yas--snippet-previous-active-field snippet)))
3210 (when (and yas-snippet-end previous-field)
3211 (yas--advance-end-maybe previous-field yas-snippet-end)))
3212
3213 ;; Convert all markers to points,
3214 ;;
3215 (yas--markers-to-points snippet)
3216
3217 ;; Take care of snippet revival
3218 ;;
3219 (if yas-snippet-revival
3220 (push `(apply yas--snippet-revive ,yas-snippet-beg ,yas-snippet-end ,snippet)
3221 buffer-undo-list)
3222 ;; Dismember the snippet... this is useful if we get called
3223 ;; again from `yas--take-care-of-redo'....
3224 (setf (yas--snippet-fields snippet) nil)))
3225
3226 (yas--message 3 "Snippet %s exited." (yas--snippet-id snippet)))
3227
3228 (defun yas--safely-run-hooks (hook-var)
3229 (condition-case error
3230 (run-hooks hook-var)
3231 (error
3232 (yas--message 3 "%s error: %s" hook-var (error-message-string error)))))
3233
3234
3235 (defun yas--check-commit-snippet ()
3236 "Checks if point exited the currently active field of the snippet.
3237
3238 If so cleans up the whole snippet up."
3239 (let* ((snippets (yas--snippets-at-point 'all-snippets))
3240 (snippets-left snippets)
3241 (snippet-exit-transform))
3242 (dolist (snippet snippets)
3243 (let ((active-field (yas--snippet-active-field snippet)))
3244 (setq snippet-exit-transform (yas--snippet-force-exit snippet))
3245 (cond ((or snippet-exit-transform
3246 (not (and active-field (yas--field-contains-point-p active-field))))
3247 (setq snippets-left (delete snippet snippets-left))
3248 (setf (yas--snippet-force-exit snippet) nil)
3249 (yas--commit-snippet snippet))
3250 ((and active-field
3251 (or (not yas--active-field-overlay)
3252 (not (overlay-buffer yas--active-field-overlay))))
3253 ;;
3254 ;; stacked expansion: this case is mainly for recent
3255 ;; snippet exits that place us back int the field of
3256 ;; another snippet
3257 ;;
3258 (save-excursion
3259 (yas--move-to-field snippet active-field)
3260 (yas--update-mirrors snippet)))
3261 (t
3262 nil))))
3263 (unless (or (null snippets) snippets-left)
3264 (if snippet-exit-transform
3265 (yas--eval-lisp-no-saves snippet-exit-transform))
3266 (yas--safely-run-hooks 'yas-after-exit-snippet-hook))))
3267
3268 ;; Apropos markers-to-points:
3269 ;;
3270 ;; This was found useful for performance reasons, so that an
3271 ;; excessive number of live markers aren't kept around in the
3272 ;; `buffer-undo-list'. However, in `markers-to-points', the
3273 ;; set-to-nil markers can't simply be discarded and replaced with
3274 ;; fresh ones in `points-to-markers'. The original marker that was
3275 ;; just set to nil has to be reused.
3276 ;;
3277 ;; This shouldn't bring horrible problems with undo/redo, but it
3278 ;; you never know
3279 ;;
3280 (defun yas--markers-to-points (snippet)
3281 "Convert all markers in SNIPPET to a cons (POINT . MARKER)
3282 where POINT is the original position of the marker and MARKER is
3283 the original marker object with the position set to nil."
3284 (dolist (field (yas--snippet-fields snippet))
3285 (let ((start (marker-position (yas--field-start field)))
3286 (end (marker-position (yas--field-end field))))
3287 (set-marker (yas--field-start field) nil)
3288 (set-marker (yas--field-end field) nil)
3289 (setf (yas--field-start field) (cons start (yas--field-start field)))
3290 (setf (yas--field-end field) (cons end (yas--field-end field))))
3291 (dolist (mirror (yas--field-mirrors field))
3292 (let ((start (marker-position (yas--mirror-start mirror)))
3293 (end (marker-position (yas--mirror-end mirror))))
3294 (set-marker (yas--mirror-start mirror) nil)
3295 (set-marker (yas--mirror-end mirror) nil)
3296 (setf (yas--mirror-start mirror) (cons start (yas--mirror-start mirror)))
3297 (setf (yas--mirror-end mirror) (cons end (yas--mirror-end mirror))))))
3298 (let ((snippet-exit (yas--snippet-exit snippet)))
3299 (when snippet-exit
3300 (let ((exit (marker-position (yas--exit-marker snippet-exit))))
3301 (set-marker (yas--exit-marker snippet-exit) nil)
3302 (setf (yas--exit-marker snippet-exit) (cons exit (yas--exit-marker snippet-exit)))))))
3303
3304 (defun yas--points-to-markers (snippet)
3305 "Convert all cons (POINT . MARKER) in SNIPPET to markers.
3306
3307 This is done by setting MARKER to POINT with `set-marker'."
3308 (dolist (field (yas--snippet-fields snippet))
3309 (setf (yas--field-start field) (set-marker (cdr (yas--field-start field))
3310 (car (yas--field-start field))))
3311 (setf (yas--field-end field) (set-marker (cdr (yas--field-end field))
3312 (car (yas--field-end field))))
3313 (dolist (mirror (yas--field-mirrors field))
3314 (setf (yas--mirror-start mirror) (set-marker (cdr (yas--mirror-start mirror))
3315 (car (yas--mirror-start mirror))))
3316 (setf (yas--mirror-end mirror) (set-marker (cdr (yas--mirror-end mirror))
3317 (car (yas--mirror-end mirror))))))
3318 (let ((snippet-exit (yas--snippet-exit snippet)))
3319 (when snippet-exit
3320 (setf (yas--exit-marker snippet-exit) (set-marker (cdr (yas--exit-marker snippet-exit))
3321 (car (yas--exit-marker snippet-exit)))))))
3322
3323 (defun yas--field-contains-point-p (field &optional point)
3324 (let ((point (or point
3325 (point))))
3326 (and (>= point (yas--field-start field))
3327 (<= point (yas--field-end field)))))
3328
3329 (defun yas--field-text-for-display (field)
3330 "Return the propertized display text for field FIELD."
3331 (buffer-substring (yas--field-start field) (yas--field-end field)))
3332
3333 (defun yas--undo-in-progress ()
3334 "True if some kind of undo is in progress."
3335 (or undo-in-progress
3336 (eq this-command 'undo)
3337 (eq this-command 'redo)))
3338
3339 (defun yas--make-control-overlay (snippet start end)
3340 "Creates the control overlay that surrounds the snippet and
3341 holds the keymap."
3342 (let ((overlay (make-overlay start
3343 end
3344 nil
3345 nil
3346 t)))
3347 (overlay-put overlay 'keymap yas-keymap)
3348 (overlay-put overlay 'priority 100)
3349 (overlay-put overlay 'yas--snippet snippet)
3350 overlay))
3351
3352 (defun yas-skip-and-clear-or-delete-char (&optional field)
3353 "Clears unmodified field if at field start, skips to next tab.
3354
3355 Otherwise deletes a character normally by calling `delete-char'."
3356 (interactive)
3357 (let ((field (or field
3358 (and yas--active-field-overlay
3359 (overlay-buffer yas--active-field-overlay)
3360 (overlay-get yas--active-field-overlay 'yas--field)))))
3361 (cond ((and field
3362 (not (yas--field-modified-p field))
3363 (eq (point) (marker-position (yas--field-start field))))
3364 (yas--skip-and-clear field)
3365 (yas-next-field 1))
3366 (t
3367 (call-interactively 'delete-char)))))
3368
3369 (defun yas--skip-and-clear (field)
3370 "Deletes the region of FIELD and sets it's modified state to t."
3371 ;; Just before skipping-and-clearing the field, mark its children
3372 ;; fields as modified, too. If the children have mirrors-in-fields
3373 ;; this prevents them from updating erroneously (we're skipping and
3374 ;; deleting!).
3375 ;;
3376 (yas--mark-this-and-children-modified field)
3377 (delete-region (yas--field-start field) (yas--field-end field)))
3378
3379 (defun yas--mark-this-and-children-modified (field)
3380 (setf (yas--field-modified-p field) t)
3381 (let ((fom (yas--field-next field)))
3382 (while (and fom
3383 (yas--fom-parent-field fom))
3384 (when (and (eq (yas--fom-parent-field fom) field)
3385 (yas--field-p fom))
3386 (yas--mark-this-and-children-modified fom))
3387 (setq fom (yas--fom-next fom)))))
3388
3389 (defun yas--make-move-active-field-overlay (snippet field)
3390 "Place the active field overlay in SNIPPET's FIELD.
3391
3392 Move the overlay, or create it if it does not exit."
3393 (if (and yas--active-field-overlay
3394 (overlay-buffer yas--active-field-overlay))
3395 (move-overlay yas--active-field-overlay
3396 (yas--field-start field)
3397 (yas--field-end field))
3398 (setq yas--active-field-overlay
3399 (make-overlay (yas--field-start field)
3400 (yas--field-end field)
3401 nil nil t))
3402 (overlay-put yas--active-field-overlay 'priority 100)
3403 (overlay-put yas--active-field-overlay 'face 'yas-field-highlight-face)
3404 (overlay-put yas--active-field-overlay 'yas--snippet snippet)
3405 (overlay-put yas--active-field-overlay 'modification-hooks '(yas--on-field-overlay-modification))
3406 (overlay-put yas--active-field-overlay 'insert-in-front-hooks
3407 '(yas--on-field-overlay-modification))
3408 (overlay-put yas--active-field-overlay 'insert-behind-hooks
3409 '(yas--on-field-overlay-modification))))
3410
3411 (defvar yas--inhibit-overlay-hooks nil
3412 "Bind this temporarily to non-nil to prevent running `yas--on-*-modification'.")
3413
3414 (defun yas--on-field-overlay-modification (overlay after? beg end &optional length)
3415 "Clears the field and updates mirrors, conditionally.
3416
3417 Only clears the field if it hasn't been modified and it point it
3418 at field start. This hook doesn't do anything if an undo is in
3419 progress."
3420 (unless (or yas--inhibit-overlay-hooks
3421 (yas--undo-in-progress))
3422 (let* ((field (overlay-get overlay 'yas--field))
3423 (number (and field (yas--field-number field)))
3424 (snippet (overlay-get yas--active-field-overlay 'yas--snippet)))
3425 (cond (after?
3426 (yas--advance-end-maybe field (overlay-end overlay))
3427 (save-excursion
3428 (yas--field-update-display field snippet))
3429 (yas--update-mirrors snippet))
3430 (field
3431 (when (and (not after?)
3432 (not (yas--field-modified-p field))
3433 (eq (point) (if (markerp (yas--field-start field))
3434 (marker-position (yas--field-start field))
3435 (yas--field-start field))))
3436 (yas--skip-and-clear field))
3437 (setf (yas--field-modified-p field) t))))))
3438 \f
3439 ;;; Apropos protection overlays:
3440 ;;
3441 ;; These exist for nasty users who will try to delete parts of the
3442 ;; snippet outside the active field. Actual protection happens in
3443 ;; `yas--on-protection-overlay-modification'.
3444 ;;
3445 ;; Currently this signals an error which inhibits the command. For
3446 ;; commands that move point (like `kill-line'), point is restored in
3447 ;; the `yas--post-command-handler' using a global
3448 ;; `yas--protection-violation' variable.
3449 ;;
3450 ;; Alternatively, I've experimented with an implementation that
3451 ;; commits the snippet before actually calling `this-command'
3452 ;; interactively, and then signals an error, which is ignored. but
3453 ;; blocks all other million modification hooks. This presented some
3454 ;; problems with stacked expansion.
3455 ;;
3456 (defun yas--make-move-field-protection-overlays (snippet field)
3457 "Place protection overlays surrounding SNIPPET's FIELD.
3458
3459 Move the overlays, or create them if they do not exit."
3460 (let ((start (yas--field-start field))
3461 (end (yas--field-end field)))
3462 ;; First check if the (1+ end) is contained in the buffer,
3463 ;; otherwise we'll have to do a bit of cheating and silently
3464 ;; insert a newline. the `(1+ (buffer-size))' should prevent this
3465 ;; when using stacked expansion
3466 ;;
3467 (when (< (buffer-size) end)
3468 (save-excursion
3469 (yas--inhibit-overlay-hooks
3470 (goto-char (point-max))
3471 (newline))))
3472 ;; go on to normal overlay creation/moving
3473 ;;
3474 (cond ((and yas--field-protection-overlays
3475 (every #'overlay-buffer yas--field-protection-overlays))
3476 (move-overlay (first yas--field-protection-overlays) (1- start) start)
3477 (move-overlay (second yas--field-protection-overlays) end (1+ end)))
3478 (t
3479 (setq yas--field-protection-overlays
3480 (list (make-overlay (1- start) start nil t nil)
3481 (make-overlay end (1+ end) nil t nil)))
3482 (dolist (ov yas--field-protection-overlays)
3483 (overlay-put ov 'face 'yas--field-debug-face)
3484 (overlay-put ov 'yas--snippet snippet)
3485 ;; (overlay-put ov 'evaporate t)
3486 (overlay-put ov 'modification-hooks '(yas--on-protection-overlay-modification)))))))
3487
3488 (defvar yas--protection-violation nil
3489 "When non-nil, signals attempts to erroneously exit or modify the snippet.
3490
3491 Functions in the `post-command-hook', for example
3492 `yas--post-command-handler' can check it and reset its value to
3493 nil. The variables value is the point where the violation
3494 originated")
3495
3496 (defun yas--on-protection-overlay-modification (overlay after? beg end &optional length)
3497 "Signals a snippet violation, then issues error.
3498
3499 The error should be ignored in `debug-ignored-errors'"
3500 (unless yas--inhibit-overlay-hooks
3501 (cond ((not (or after?
3502 (yas--undo-in-progress)))
3503 (setq yas--protection-violation (point))
3504 (error "Exit the snippet first!")))))
3505
3506 (add-to-list 'debug-ignored-errors "^Exit the snippet first!$")
3507
3508 \f
3509 ;;; Snippet expansion and "stacked" expansion:
3510 ;;
3511 ;; Stacked expansion is when you try to expand a snippet when already
3512 ;; inside a snippet expansion.
3513 ;;
3514 ;; The parent snippet does not run its fields modification hooks
3515 ;; (`yas--on-field-overlay-modification' and
3516 ;; `yas--on-protection-overlay-modification') while the child snippet
3517 ;; is active. This means, among other things, that the mirrors of the
3518 ;; parent snippet are not updated, this only happening when one exits
3519 ;; the child snippet.
3520 ;;
3521 ;; Unfortunately, this also puts some ugly (and not fully-tested)
3522 ;; bits of code in `yas-expand-snippet' and
3523 ;; `yas--commit-snippet'. I've tried to mark them with "stacked
3524 ;; expansion:".
3525 ;;
3526 ;; This was thought to be safer in an undo/redo perspective, but
3527 ;; maybe the correct implementation is to make the globals
3528 ;; `yas--active-field-overlay' and `yas--field-protection-overlays' be
3529 ;; snippet-local and be active even while the child snippet is
3530 ;; running. This would mean a lot of overlay modification hooks
3531 ;; running, but if managed correctly (including overlay priorities)
3532 ;; they should account for all situations...
3533 ;;
3534 (defun yas-expand-snippet (content &optional start end expand-env)
3535 "Expand snippet CONTENT at current point.
3536
3537 Text between START and END will be deleted before inserting
3538 template. EXPAND-ENV is are let-style variable to value bindings
3539 considered when expanding the snippet."
3540 (run-hooks 'yas-before-expand-snippet-hook)
3541
3542 ;;
3543 (let* ((yas-selected-text (or yas-selected-text
3544 (and (region-active-p)
3545 (buffer-substring-no-properties (region-beginning)
3546 (region-end)))))
3547 (start (or start
3548 (and (region-active-p)
3549 (region-beginning))
3550 (point)))
3551 (end (or end
3552 (and (region-active-p)
3553 (region-end))
3554 (point)))
3555 (to-delete (and start
3556 end
3557 (buffer-substring-no-properties start end)))
3558 snippet)
3559 (goto-char start)
3560 (setq yas--indent-original-column (current-column))
3561 ;; Delete the region to delete, this *does* get undo-recorded.
3562 ;;
3563 (when (and to-delete
3564 (> end start))
3565 (delete-region start end))
3566
3567 (cond ((listp content)
3568 ;; x) This is a snippet-command
3569 ;;
3570 (yas--eval-lisp-no-saves content))
3571 (t
3572 ;; x) This is a snippet-snippet :-)
3573 ;;
3574 ;; Narrow the region down to the content, shoosh the
3575 ;; `buffer-undo-list', and create the snippet, the new
3576 ;; snippet updates its mirrors once, so we are left with
3577 ;; some plain text. The undo action for deleting this
3578 ;; plain text will get recorded at the end.
3579 ;;
3580 ;; stacked expansion: also shoosh the overlay modification hooks
3581 (save-restriction
3582 (narrow-to-region start start)
3583 (let ((buffer-undo-list t))
3584 ;; snippet creation might evaluate users elisp, which
3585 ;; might generate errors, so we have to be ready to catch
3586 ;; them mostly to make the undo information
3587 ;;
3588 (setq yas--start-column (save-restriction (widen) (current-column)))
3589 (yas--inhibit-overlay-hooks
3590 (setq snippet
3591 (if expand-env
3592 (eval `(let* ,expand-env
3593 (insert content)
3594 (yas--snippet-create (point-min) (point-max))))
3595 (insert content)
3596 (yas--snippet-create (point-min) (point-max)))))))
3597
3598 ;; stacked-expansion: This checks for stacked expansion, save the
3599 ;; `yas--previous-active-field' and advance its boundary.
3600 ;;
3601 (let ((existing-field (and yas--active-field-overlay
3602 (overlay-buffer yas--active-field-overlay)
3603 (overlay-get yas--active-field-overlay 'yas--field))))
3604 (when existing-field
3605 (setf (yas--snippet-previous-active-field snippet) existing-field)
3606 (yas--advance-end-maybe existing-field (overlay-end yas--active-field-overlay))))
3607
3608 ;; Exit the snippet immediately if no fields
3609 ;;
3610 (unless (yas--snippet-fields snippet)
3611 (yas-exit-snippet snippet))
3612
3613 ;; Push two undo actions: the deletion of the inserted contents of
3614 ;; the new snippet (without the "key") followed by an apply of
3615 ;; `yas--take-care-of-redo' on the newly inserted snippet boundaries
3616 ;;
3617 ;; A small exception, if `yas-also-auto-indent-first-line'
3618 ;; is t and `yas--indent' decides to indent the line to a
3619 ;; point before the actual expansion point, undo would be
3620 ;; messed up. We call the early point "newstart"". case,
3621 ;; and attempt to fix undo.
3622 ;;
3623 (let ((newstart (overlay-start (yas--snippet-control-overlay snippet)))
3624 (end (overlay-end (yas--snippet-control-overlay snippet))))
3625 (when (< newstart start)
3626 (push (cons (make-string (- start newstart) ? ) newstart) buffer-undo-list))
3627 (push (cons newstart end) buffer-undo-list)
3628 (push `(apply yas--take-care-of-redo ,start ,end ,snippet)
3629 buffer-undo-list))
3630 ;; Now, schedule a move to the first field
3631 ;;
3632 (let ((first-field (car (yas--snippet-fields snippet))))
3633 (when first-field
3634 (sit-for 0) ;; fix issue 125
3635 (yas--move-to-field snippet first-field)))
3636 (yas--message 3 "snippet expanded.")
3637 t))))
3638
3639 (defun yas--take-care-of-redo (beg end snippet)
3640 "Commits SNIPPET, which in turn pushes an undo action for reviving it.
3641
3642 Meant to exit in the `buffer-undo-list'."
3643 ;; slightly optimize: this action is only needed for snippets with
3644 ;; at least one field
3645 (when (yas--snippet-fields snippet)
3646 (yas--commit-snippet snippet)))
3647
3648 (defun yas--snippet-revive (beg end snippet)
3649 "Revives SNIPPET and creates a control overlay from BEG to END.
3650
3651 BEG and END are, we hope, the original snippets boundaries. All
3652 the markers/points exiting existing inside SNIPPET should point
3653 to their correct locations *at the time the snippet is revived*.
3654
3655 After revival, push the `yas--take-care-of-redo' in the
3656 `buffer-undo-list'"
3657 ;; Reconvert all the points to markers
3658 ;;
3659 (yas--points-to-markers snippet)
3660 ;; When at least one editable field existed in the zombie snippet,
3661 ;; try to revive the whole thing...
3662 ;;
3663 (let ((target-field (or (yas--snippet-active-field snippet)
3664 (car (yas--snippet-fields snippet)))))
3665 (when target-field
3666 (setf (yas--snippet-control-overlay snippet) (yas--make-control-overlay snippet beg end))
3667 (overlay-put (yas--snippet-control-overlay snippet) 'yas--snippet snippet)
3668
3669 (yas--move-to-field snippet target-field)
3670
3671 (push `(apply yas--take-care-of-redo ,beg ,end ,snippet)
3672 buffer-undo-list))))
3673
3674 (defun yas--snippet-create (begin end)
3675 "Creates a snippet from an template inserted between BEGIN and END.
3676
3677 Returns the newly created snippet."
3678 (let ((snippet (yas--make-snippet)))
3679 (goto-char begin)
3680 (yas--snippet-parse-create snippet)
3681
3682 ;; Sort and link each field
3683 (yas--snippet-sort-fields snippet)
3684
3685 ;; Create keymap overlay for snippet
3686 (setf (yas--snippet-control-overlay snippet)
3687 (yas--make-control-overlay snippet (point-min) (point-max)))
3688
3689 ;; Move to end
3690 (goto-char (point-max))
3691
3692 snippet))
3693
3694 \f
3695 ;;; Apropos adjacencies and "fom's":
3696 ;;
3697 ;; Once the $-constructs bits like "$n" and "${:n" are deleted in the
3698 ;; recently expanded snippet, we might actually have many fields,
3699 ;; mirrors (and the snippet exit) in the very same position in the
3700 ;; buffer. Therefore we need to single-link the
3701 ;; fields-or-mirrors-or-exit (which I have abbreviated to "fom")
3702 ;; according to their original positions in the buffer.
3703 ;;
3704 ;; Then we have operation `yas--advance-end-maybe' and
3705 ;; `yas--advance-start-maybe', which conditionally push the starts and
3706 ;; ends of these foms down the chain.
3707 ;;
3708 ;; This allows for like the printf with the magic ",":
3709 ;;
3710 ;; printf ("${1:%s}\\n"${1:$(if (string-match "%" text) "," "\);")} \
3711 ;; $2${1:$(if (string-match "%" text) "\);" "")}$0
3712 ;;
3713 (defun yas--fom-start (fom)
3714 (cond ((yas--field-p fom)
3715 (yas--field-start fom))
3716 ((yas--mirror-p fom)
3717 (yas--mirror-start fom))
3718 (t
3719 (yas--exit-marker fom))))
3720
3721 (defun yas--fom-end (fom)
3722 (cond ((yas--field-p fom)
3723 (yas--field-end fom))
3724 ((yas--mirror-p fom)
3725 (yas--mirror-end fom))
3726 (t
3727 (yas--exit-marker fom))))
3728
3729 (defun yas--fom-next (fom)
3730 (cond ((yas--field-p fom)
3731 (yas--field-next fom))
3732 ((yas--mirror-p fom)
3733 (yas--mirror-next fom))
3734 (t
3735 (yas--exit-next fom))))
3736
3737 (defun yas--fom-parent-field (fom)
3738 (cond ((yas--field-p fom)
3739 (yas--field-parent-field fom))
3740 ((yas--mirror-p fom)
3741 (yas--mirror-parent-field fom))
3742 (t
3743 nil)))
3744
3745 (defun yas--calculate-adjacencies (snippet)
3746 "Calculate adjacencies for fields or mirrors of SNIPPET.
3747
3748 This is according to their relative positions in the buffer, and
3749 has to be called before the $-constructs are deleted."
3750 (labels ((yas--fom-set-next-fom (fom nextfom)
3751 (cond ((yas--field-p fom)
3752 (setf (yas--field-next fom) nextfom))
3753 ((yas--mirror-p fom)
3754 (setf (yas--mirror-next fom) nextfom))
3755 (t
3756 (setf (yas--exit-next fom) nextfom))))
3757 (yas--compare-fom-begs (fom1 fom2)
3758 (if (= (yas--fom-start fom2) (yas--fom-start fom1))
3759 (yas--mirror-p fom2)
3760 (>= (yas--fom-start fom2) (yas--fom-start fom1))))
3761 (yas--link-foms (fom1 fom2)
3762 (yas--fom-set-next-fom fom1 fom2)))
3763 ;; make some yas--field, yas--mirror and yas--exit soup
3764 (let ((soup))
3765 (when (yas--snippet-exit snippet)
3766 (push (yas--snippet-exit snippet) soup))
3767 (dolist (field (yas--snippet-fields snippet))
3768 (push field soup)
3769 (dolist (mirror (yas--field-mirrors field))
3770 (push mirror soup)))
3771 (setq soup
3772 (sort soup
3773 #'yas--compare-fom-begs))
3774 (when soup
3775 (reduce #'yas--link-foms soup)))))
3776
3777 (defun yas--calculate-mirrors-in-fields (snippet mirror)
3778 "Attempt to assign a parent field of SNIPPET to the mirror MIRROR.
3779
3780 Use the tightest containing field if more than one field contains
3781 the mirror. Intended to be called *before* the dollar-regions are
3782 deleted."
3783 (let ((min (point-min))
3784 (max (point-max)))
3785 (dolist (field (yas--snippet-fields snippet))
3786 (when (and (<= (yas--field-start field) (yas--mirror-start mirror))
3787 (<= (yas--mirror-end mirror) (yas--field-end field))
3788 (< min (yas--field-start field))
3789 (< (yas--field-end field) max))
3790 (setq min (yas--field-start field)
3791 max (yas--field-end field))
3792 (setf (yas--mirror-parent-field mirror) field)))))
3793
3794 (defun yas--advance-end-maybe (fom newend)
3795 "Maybe advance FOM's end to NEWEND if it needs it.
3796
3797 If it does, also:
3798
3799 * call `yas--advance-start-maybe' on FOM's next fom.
3800
3801 * in case FOM is field call `yas--advance-end-maybe' on its parent
3802 field
3803
3804 Also, if FOM is an exit-marker, always call
3805 `yas--advance-start-maybe' on its next fom. This is because
3806 exit-marker have identical start and end markers."
3807 (cond ((and fom (< (yas--fom-end fom) newend))
3808 (set-marker (yas--fom-end fom) newend)
3809 (yas--advance-start-maybe (yas--fom-next fom) newend)
3810 (yas--advance-end-of-parents-maybe (yas--fom-parent-field fom) newend))
3811 ((yas--exit-p fom)
3812 (yas--advance-start-maybe (yas--fom-next fom) newend))))
3813
3814 (defun yas--advance-start-maybe (fom newstart)
3815 "Maybe advance FOM's start to NEWSTART if it needs it.
3816
3817 If it does, also call `yas--advance-end-maybe' on FOM."
3818 (when (and fom (< (yas--fom-start fom) newstart))
3819 (set-marker (yas--fom-start fom) newstart)
3820 (yas--advance-end-maybe fom newstart)))
3821
3822 (defun yas--advance-end-of-parents-maybe (field newend)
3823 "Like `yas--advance-end-maybe' but for parent fields.
3824
3825 Only works for fields and doesn't care about the start of the
3826 next FOM. Works its way up recursively for parents of parents."
3827 (when (and field
3828 (< (yas--field-end field) newend))
3829 (set-marker (yas--field-end field) newend)
3830 (yas--advance-end-of-parents-maybe (yas--field-parent-field field) newend)))
3831
3832 (defvar yas--dollar-regions nil
3833 "When expanding the snippet the \"parse-create\" functions add
3834 cons cells to this var.")
3835
3836 (defvar yas--backquote-markers-and-strings nil
3837 "List of (MARKER . STRING) marking where the values from
3838 backquoted lisp expressions should be inserted at the end of
3839 expansion.")
3840
3841 (defun yas--snippet-parse-create (snippet)
3842 "Parse a recently inserted snippet template, creating all
3843 necessary fields, mirrors and exit points.
3844
3845 Meant to be called in a narrowed buffer, does various passes"
3846 (let ((parse-start (point)))
3847 ;; Reset the yas--dollar-regions
3848 ;;
3849 (setq yas--dollar-regions nil)
3850 ;; protect just the backquotes
3851 ;;
3852 (yas--protect-escapes nil '(?`))
3853 ;; replace all backquoted expressions
3854 ;;
3855 (goto-char parse-start)
3856 (yas--save-backquotes)
3857 ;; protect escaped characters
3858 ;;
3859 (yas--protect-escapes)
3860 ;; parse fields with {}
3861 ;;
3862 (goto-char parse-start)
3863 (yas--field-parse-create snippet)
3864 ;; parse simple mirrors and fields
3865 ;;
3866 (goto-char parse-start)
3867 (yas--simple-mirror-parse-create snippet)
3868 ;; parse mirror transforms
3869 ;;
3870 (goto-char parse-start)
3871 (yas--transform-mirror-parse-create snippet)
3872 ;; calculate adjacencies of fields and mirrors
3873 ;;
3874 (yas--calculate-adjacencies snippet)
3875 ;; Delete $-constructs
3876 ;;
3877 (yas--delete-regions yas--dollar-regions)
3878 ;; restore backquoted expression values
3879 ;;
3880 (yas--restore-backquotes)
3881 ;; restore escapes
3882 ;;
3883 (goto-char parse-start)
3884 (yas--restore-escapes)
3885 ;; update mirrors for the first time
3886 ;;
3887 (yas--update-mirrors snippet)
3888 ;; indent the best we can
3889 ;;
3890 (goto-char parse-start)
3891 (yas--indent snippet)))
3892
3893 (defun yas--indent-according-to-mode (snippet-markers)
3894 "Indent current line according to mode, preserving SNIPPET-MARKERS."
3895 ;;; Apropos indenting problems....
3896 ;;
3897 ;; `indent-according-to-mode' uses whatever `indent-line-function'
3898 ;; is available. Some implementations of these functions delete text
3899 ;; before they insert. If there happens to be a marker just after
3900 ;; the text being deleted, the insertion actually happens after the
3901 ;; marker, which misplaces it.
3902 ;;
3903 ;; This would also happen if we had used overlays with the
3904 ;; `front-advance' property set to nil.
3905 ;;
3906 ;; This is why I have these `trouble-markers', they are the ones at
3907 ;; they are the ones at the first non-whitespace char at the line
3908 ;; (i.e. at `yas--real-line-beginning'. After indentation takes place
3909 ;; we should be at the correct to restore them to. All other
3910 ;; non-trouble-markers have been *pushed* and don't need special
3911 ;; attention.
3912 ;;
3913 (goto-char (yas--real-line-beginning))
3914 (let ((trouble-markers (remove-if-not #'(lambda (marker)
3915 (= marker (point)))
3916 snippet-markers)))
3917 (save-restriction
3918 (widen)
3919 (condition-case err
3920 (indent-according-to-mode)
3921 (error (yas--message 3 "Warning: `yas--indent-according-to-mode' having problems running %s" indent-line-function)
3922 nil)))
3923 (mapc #'(lambda (marker)
3924 (set-marker marker (point)))
3925 trouble-markers)))
3926
3927 (defvar yas--indent-original-column nil)
3928 (defun yas--indent (snippet)
3929 (let ((snippet-markers (yas--collect-snippet-markers snippet)))
3930 ;; Look for those $>
3931 (save-excursion
3932 (while (re-search-forward "$>" nil t)
3933 (delete-region (match-beginning 0) (match-end 0))
3934 (when (not (eq yas-indent-line 'auto))
3935 (yas--indent-according-to-mode snippet-markers))))
3936 ;; Now do stuff for 'fixed and 'auto
3937 (save-excursion
3938 (cond ((eq yas-indent-line 'fixed)
3939 (while (and (zerop (forward-line))
3940 (zerop (current-column)))
3941 (indent-to-column yas--indent-original-column)))
3942 ((eq yas-indent-line 'auto)
3943 (let ((end (set-marker (make-marker) (point-max)))
3944 (indent-first-line-p yas-also-auto-indent-first-line))
3945 (while (and (zerop (if indent-first-line-p
3946 (prog1
3947 (forward-line 0)
3948 (setq indent-first-line-p nil))
3949 (forward-line 1)))
3950 (not (eobp))
3951 (<= (point) end))
3952 (yas--indent-according-to-mode snippet-markers))))
3953 (t
3954 nil)))))
3955
3956 (defun yas--collect-snippet-markers (snippet)
3957 "Make a list of all the markers used by SNIPPET."
3958 (let (markers)
3959 (dolist (field (yas--snippet-fields snippet))
3960 (push (yas--field-start field) markers)
3961 (push (yas--field-end field) markers)
3962 (dolist (mirror (yas--field-mirrors field))
3963 (push (yas--mirror-start mirror) markers)
3964 (push (yas--mirror-end mirror) markers)))
3965 (let ((snippet-exit (yas--snippet-exit snippet)))
3966 (when (and snippet-exit
3967 (marker-buffer (yas--exit-marker snippet-exit)))
3968 (push (yas--exit-marker snippet-exit) markers)))
3969 markers))
3970
3971 (defun yas--real-line-beginning ()
3972 (let ((c (char-after (line-beginning-position)))
3973 (n (line-beginning-position)))
3974 (while (or (eql c ?\ )
3975 (eql c ?\t))
3976 (incf n)
3977 (setq c (char-after n)))
3978 n))
3979
3980 (defun yas--escape-string (escaped)
3981 (concat "YASESCAPE" (format "%d" escaped) "PROTECTGUARD"))
3982
3983 (defun yas--protect-escapes (&optional text escaped)
3984 "Protect all escaped characters with their numeric ASCII value.
3985
3986 With optional string TEXT do it in string instead of buffer."
3987 (let ((changed-text text)
3988 (text-provided-p text))
3989 (mapc #'(lambda (escaped)
3990 (setq changed-text
3991 (yas--replace-all (concat "\\" (char-to-string escaped))
3992 (yas--escape-string escaped)
3993 (when text-provided-p changed-text))))
3994 (or escaped yas--escaped-characters))
3995 changed-text))
3996
3997 (defun yas--restore-escapes (&optional text escaped)
3998 "Restore all escaped characters from their numeric ASCII value.
3999
4000 With optional string TEXT do it in string instead of the buffer."
4001 (let ((changed-text text)
4002 (text-provided-p text))
4003 (mapc #'(lambda (escaped)
4004 (setq changed-text
4005 (yas--replace-all (yas--escape-string escaped)
4006 (char-to-string escaped)
4007 (when text-provided-p changed-text))))
4008 (or escaped yas--escaped-characters))
4009 changed-text))
4010
4011 (defun yas--save-backquotes ()
4012 "Save all the \"`(lisp-expression)`\"-style expressions
4013 with their evaluated value into `yas--backquote-markers-and-strings'."
4014 (while (re-search-forward yas--backquote-lisp-expression-regexp nil t)
4015 (let ((current-string (match-string-no-properties 1)) transformed)
4016 (delete-region (match-beginning 0) (match-end 0))
4017 (setq transformed (yas--eval-lisp (yas--read-lisp (yas--restore-escapes current-string '(?`)))))
4018 (goto-char (match-beginning 0))
4019 (when transformed
4020 (let ((marker (make-marker)))
4021 (insert "Y") ;; quite horrendous, I love it :)
4022 (set-marker marker (point))
4023 (insert "Y")
4024 (push (cons marker transformed) yas--backquote-markers-and-strings))))))
4025
4026 (defun yas--restore-backquotes ()
4027 "Replace markers in `yas--backquote-markers-and-strings' with their values."
4028 (while yas--backquote-markers-and-strings
4029 (let* ((marker-and-string (pop yas--backquote-markers-and-strings))
4030 (marker (car marker-and-string))
4031 (string (cdr marker-and-string)))
4032 (save-excursion
4033 (goto-char marker)
4034 (delete-char -1)
4035 (insert string)
4036 (delete-char 1)
4037 (set-marker marker nil)))))
4038
4039 (defun yas--scan-sexps (from count)
4040 (condition-case err
4041 (with-syntax-table (standard-syntax-table)
4042 (scan-sexps from count))
4043 (error
4044 nil)))
4045
4046 (defun yas--make-marker (pos)
4047 "Create a marker at POS with nil `marker-insertion-type'."
4048 (let ((marker (set-marker (make-marker) pos)))
4049 (set-marker-insertion-type marker nil)
4050 marker))
4051
4052 (defun yas--field-parse-create (snippet &optional parent-field)
4053 "Parse most field expressions in SNIPPET, except for the simple one \"$n\".
4054
4055 The following count as a field:
4056
4057 * \"${n: text}\", for a numbered field with default text, as long as N is not 0;
4058
4059 * \"${n: text$(expression)}, the same with a lisp expression;
4060 this is caught with the curiously named `yas--multi-dollar-lisp-expression-regexp'
4061
4062 * the same as above but unnumbered, (no N:) and number is calculated automatically.
4063
4064 When multiple expressions are found, only the last one counts."
4065 ;;
4066 (save-excursion
4067 (while (re-search-forward yas--field-regexp nil t)
4068 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4069 (number (and (match-string-no-properties 1)
4070 (string-to-number (match-string-no-properties 1))))
4071 (brand-new-field (and real-match-end-0
4072 ;; break if on "$(" immediately
4073 ;; after the ":", this will be
4074 ;; caught as a mirror with
4075 ;; transform later.
4076 (not (save-match-data
4077 (eq (string-match "$[ \t\n]*("
4078 (match-string-no-properties 2)) 0)))
4079 ;; allow ${0: some exit text}
4080 ;; (not (and number (zerop number)))
4081 (yas--make-field number
4082 (yas--make-marker (match-beginning 2))
4083 (yas--make-marker (1- real-match-end-0))
4084 parent-field))))
4085 (when brand-new-field
4086 (goto-char real-match-end-0)
4087 (push (cons (1- real-match-end-0) real-match-end-0)
4088 yas--dollar-regions)
4089 (push (cons (match-beginning 0) (match-beginning 2))
4090 yas--dollar-regions)
4091 (push brand-new-field (yas--snippet-fields snippet))
4092 (save-excursion
4093 (save-restriction
4094 (narrow-to-region (yas--field-start brand-new-field) (yas--field-end brand-new-field))
4095 (goto-char (point-min))
4096 (yas--field-parse-create snippet brand-new-field)))))))
4097 ;; if we entered from a parent field, now search for the
4098 ;; `yas--multi-dollar-lisp-expression-regexp'. This is used for
4099 ;; primary field transformations
4100 ;;
4101 (when parent-field
4102 (save-excursion
4103 (while (re-search-forward yas--multi-dollar-lisp-expression-regexp nil t)
4104 (let* ((real-match-end-1 (yas--scan-sexps (match-beginning 1) 1)))
4105 ;; commit the primary field transformation if:
4106 ;;
4107 ;; 1. we don't find it in yas--dollar-regions (a subnested
4108 ;; field) might have already caught it.
4109 ;;
4110 ;; 2. we really make sure we have either two '$' or some
4111 ;; text and a '$' after the colon ':'. This is a FIXME: work
4112 ;; my regular expressions and end these ugly hacks.
4113 ;;
4114 (when (and real-match-end-1
4115 (not (member (cons (match-beginning 0)
4116 real-match-end-1)
4117 yas--dollar-regions))
4118 (not (eq ?:
4119 (char-before (1- (match-beginning 1))))))
4120 (let ((lisp-expression-string (buffer-substring-no-properties (match-beginning 1)
4121 real-match-end-1)))
4122 (setf (yas--field-transform parent-field)
4123 (yas--read-lisp (yas--restore-escapes lisp-expression-string))))
4124 (push (cons (match-beginning 0) real-match-end-1)
4125 yas--dollar-regions)))))))
4126
4127 (defun yas--transform-mirror-parse-create (snippet)
4128 "Parse the \"${n:$(lisp-expression)}\" mirror transformations in SNIPPET."
4129 (while (re-search-forward yas--transform-mirror-regexp nil t)
4130 (let* ((real-match-end-0 (yas--scan-sexps (1+ (match-beginning 0)) 1))
4131 (number (string-to-number (match-string-no-properties 1)))
4132 (field (and number
4133 (not (zerop number))
4134 (yas--snippet-find-field snippet number)))
4135 (brand-new-mirror
4136 (and real-match-end-0
4137 field
4138 (yas--make-mirror (yas--make-marker (match-beginning 0))
4139 (yas--make-marker (match-beginning 0))
4140 (yas--read-lisp
4141 (yas--restore-escapes
4142 (buffer-substring-no-properties (match-beginning 2)
4143 (1- real-match-end-0))))))))
4144 (when brand-new-mirror
4145 (push brand-new-mirror
4146 (yas--field-mirrors field))
4147 (yas--calculate-mirrors-in-fields snippet brand-new-mirror)
4148 (push (cons (match-beginning 0) real-match-end-0) yas--dollar-regions)))))
4149
4150 (defun yas--simple-mirror-parse-create (snippet)
4151 "Parse the simple \"$n\" fields/mirrors/exitmarkers in SNIPPET."
4152 (while (re-search-forward yas--simple-mirror-regexp nil t)
4153 (let ((number (string-to-number (match-string-no-properties 1))))
4154 (cond ((zerop number)
4155
4156 (setf (yas--snippet-exit snippet)
4157 (yas--make-exit (yas--make-marker (match-end 0))))
4158 (save-excursion
4159 (goto-char (match-beginning 0))
4160 (when yas-wrap-around-region
4161 (cond (yas-selected-text
4162 (insert yas-selected-text))
4163 ((and (eq yas-wrap-around-region 'cua)
4164 cua-mode
4165 (get-register ?0))
4166 (insert (prog1 (get-register ?0)
4167 (set-register ?0 nil))))))
4168 (push (cons (point) (yas--exit-marker (yas--snippet-exit snippet)))
4169 yas--dollar-regions)))
4170 (t
4171 (let ((field (yas--snippet-find-field snippet number)))
4172 (if field
4173 (let ((brand-new-mirror (yas--make-mirror
4174 (yas--make-marker (match-beginning 0))
4175 (yas--make-marker (match-beginning 0))
4176 nil)))
4177 (push brand-new-mirror
4178 (yas--field-mirrors field))
4179 (yas--calculate-mirrors-in-fields snippet brand-new-mirror))
4180 (push (yas--make-field number
4181 (yas--make-marker (match-beginning 0))
4182 (yas--make-marker (match-beginning 0))
4183 nil)
4184 (yas--snippet-fields snippet))))
4185 (push (cons (match-beginning 0) (match-end 0))
4186 yas--dollar-regions))))))
4187
4188 (defun yas--delete-regions (regions)
4189 "Sort disjuct REGIONS by start point, then delete from the back."
4190 (mapc #'(lambda (reg)
4191 (delete-region (car reg) (cdr reg)))
4192 (sort regions
4193 #'(lambda (r1 r2)
4194 (>= (car r1) (car r2))))))
4195
4196 (defun yas--calculate-mirror-depth (mirror &optional traversed)
4197 (let* ((parent (yas--mirror-parent-field mirror))
4198 (parents-mirrors (and parent
4199 (yas--field-mirrors parent))))
4200 (or (yas--mirror-depth mirror)
4201 (setf (yas--mirror-depth mirror)
4202 (cond ((memq mirror traversed)
4203 0)
4204 ((and parent parents-mirrors)
4205 (1+ (reduce #'max
4206 (mapcar #'(lambda (m)
4207 (yas--calculate-mirror-depth m
4208 (cons mirror
4209 traversed)))
4210 parents-mirrors))))
4211 (parent
4212 1)
4213 (t
4214 0))))))
4215
4216 (defun yas--update-mirrors (snippet)
4217 "Updates all the mirrors of SNIPPET."
4218 (save-excursion
4219 (dolist (field-and-mirror (sort
4220 ;; make a list of ((F1 . M1) (F1 . M2) (F2 . M3) (F2 . M4) ...)
4221 ;; where F is the field that M is mirroring
4222 ;;
4223 (mapcan #'(lambda (field)
4224 (mapcar #'(lambda (mirror)
4225 (cons field mirror))
4226 (yas--field-mirrors field)))
4227 (yas--snippet-fields snippet))
4228 ;; then sort this list so that entries with mirrors with parent
4229 ;; fields appear before. This was important for fixing #290, and
4230 ;; luckily also handles the case where a mirror in a field causes
4231 ;; another mirror to need reupdating
4232 ;;
4233 #'(lambda (field-and-mirror1 field-and-mirror2)
4234 (> (yas--calculate-mirror-depth (cdr field-and-mirror1))
4235 (yas--calculate-mirror-depth (cdr field-and-mirror2))))))
4236 (let* ((field (car field-and-mirror))
4237 (mirror (cdr field-and-mirror))
4238 (parent-field (yas--mirror-parent-field mirror)))
4239 ;; before updating a mirror with a parent-field, maybe advance
4240 ;; its start (#290)
4241 ;;
4242 (when parent-field
4243 (yas--advance-start-maybe mirror (yas--fom-start parent-field)))
4244 ;; update this mirror
4245 ;;
4246 (yas--mirror-update-display mirror field)
4247 ;; `yas--place-overlays' is needed if the active field and
4248 ;; protected overlays have been changed because of insertions
4249 ;; in `yas--mirror-update-display'
4250 ;;
4251 (when (eq field (yas--snippet-active-field snippet))
4252 (yas--place-overlays snippet field))))))
4253
4254 (defun yas--mirror-update-display (mirror field)
4255 "Update MIRROR according to FIELD (and mirror transform)."
4256
4257 (let* ((mirror-parent-field (yas--mirror-parent-field mirror))
4258 (reflection (and (not (and mirror-parent-field
4259 (yas--field-modified-p mirror-parent-field)))
4260 (or (yas--apply-transform mirror field 'empty-on-nil)
4261 (yas--field-text-for-display field)))))
4262 (when (and reflection
4263 (not (string= reflection (buffer-substring-no-properties (yas--mirror-start mirror)
4264 (yas--mirror-end mirror)))))
4265 (goto-char (yas--mirror-start mirror))
4266 (yas--inhibit-overlay-hooks
4267 (insert reflection))
4268 (if (> (yas--mirror-end mirror) (point))
4269 (delete-region (point) (yas--mirror-end mirror))
4270 (set-marker (yas--mirror-end mirror) (point))
4271 (yas--advance-start-maybe (yas--mirror-next mirror) (point))
4272 ;; super-special advance
4273 (yas--advance-end-of-parents-maybe mirror-parent-field (point))))))
4274
4275 (defun yas--field-update-display (field snippet)
4276 "Much like `yas--mirror-update-display', but for fields."
4277 (when (yas--field-transform field)
4278 (let ((transformed (and (not (eq (yas--field-number field) 0))
4279 (yas--apply-transform field field)))
4280 (point (point)))
4281 (when (and transformed
4282 (not (string= transformed (buffer-substring-no-properties (yas--field-start field)
4283 (yas--field-end field)))))
4284 (setf (yas--field-modified-p field) t)
4285 (goto-char (yas--field-start field))
4286 (yas--inhibit-overlay-hooks
4287 (insert transformed)
4288 (if (> (yas--field-end field) (point))
4289 (delete-region (point) (yas--field-end field))
4290 (set-marker (yas--field-end field) (point))
4291 (yas--advance-start-maybe (yas--field-next field) (point)))
4292 t)))))
4293
4294 \f
4295 ;;; Post-command hook:
4296 ;;
4297 (defun yas--post-command-handler ()
4298 "Handles various yasnippet conditions after each command."
4299 (cond (yas--protection-violation
4300 (goto-char yas--protection-violation)
4301 (setq yas--protection-violation nil))
4302 ((eq 'undo this-command)
4303 ;;
4304 ;; After undo revival the correct field is sometimes not
4305 ;; restored correctly, this condition handles that
4306 ;;
4307 (let* ((snippet (car (yas--snippets-at-point)))
4308 (target-field (and snippet
4309 (find-if-not #'(lambda (field)
4310 (yas--field-probably-deleted-p snippet field))
4311 (remove nil
4312 (cons (yas--snippet-active-field snippet)
4313 (yas--snippet-fields snippet)))))))
4314 (when target-field
4315 (yas--move-to-field snippet target-field))))
4316 ((not (yas--undo-in-progress))
4317 ;; When not in an undo, check if we must commit the snippet
4318 ;; (user exited it).
4319 (yas--check-commit-snippet))))
4320 \f
4321 ;;; Fancy docs:
4322 ;;
4323 ;; The docstrings for some functions are generated dynamically
4324 ;; depending on the context.
4325 ;;
4326 (put 'yas-expand 'function-documentation
4327 '(yas--expand-from-trigger-key-doc))
4328 (defun yas--expand-from-trigger-key-doc ()
4329 "A doc synthesizer for `yas--expand-from-trigger-key-doc'."
4330 (let ((fallback-description
4331 (cond ((eq yas-fallback-behavior 'call-other-command)
4332 (let* ((fallback (yas--keybinding-beyond-yasnippet)))
4333 (or (and fallback
4334 (format " call command `%s'." (pp-to-string fallback)))
4335 " do nothing (`yas-expand' doesn't shadow\nanything)")))
4336 ((eq yas-fallback-behavior 'return-nil)
4337 ", do nothing.")
4338 (t
4339 ", defer to `yas-fallback-behaviour' (which see)"))))
4340 (concat "Expand a snippet before point. If no snippet
4341 expansion is possible,"
4342 fallback-description
4343 "\n\nOptional argument FIELD is for non-interactive use and is an
4344 object satisfying `yas--field-p' to restrict the expansion to.")))
4345
4346 (put 'yas-expand-from-keymap 'function-documentation '(yas--expand-from-keymap-doc))
4347 (defun yas--expand-from-keymap-doc ()
4348 "A doc synthesizer for `yas--expand-from-keymap-doc'."
4349 (add-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce)
4350 (concat "Expand/run snippets from keymaps, possibly falling back to original binding.\n"
4351 (when (eq this-command 'describe-key)
4352 (let* ((vec (this-single-command-keys))
4353 (templates (mapcan #'(lambda (table)
4354 (yas--fetch table vec))
4355 (yas--get-snippet-tables)))
4356 (yas--direct-keymaps nil)
4357 (fallback (key-binding vec)))
4358 (concat "In this case, "
4359 (when templates
4360 (concat "these snippets are bound to this key:\n"
4361 (yas--template-pretty-list templates)
4362 "\n\nIf none of these expands, "))
4363 (or (and fallback
4364 (format "fallback `%s' will be called." (pp-to-string fallback)))
4365 "no fallback keybinding is called."))))))
4366
4367 (defun yas--template-pretty-list (templates)
4368 (let ((acc)
4369 (yas-buffer-local-condition 'always))
4370 (dolist (plate templates)
4371 (setq acc (concat acc "\n*) "
4372 (propertize (concat "\\\\snippet `" (car plate) "'")
4373 'yasnippet (cdr plate)))))
4374 acc))
4375
4376 (define-button-type 'help-snippet-def
4377 :supertype 'help-xref
4378 'help-function (lambda (template) (yas--visit-snippet-file-1 template))
4379 'help-echo (purecopy "mouse-2, RET: find snippets's definition"))
4380
4381 (defun yas--snippet-description-finish-runonce ()
4382 "Final adjustments for the help buffer when snippets are concerned."
4383 (yas--create-snippet-xrefs)
4384 (remove-hook 'temp-buffer-show-hook 'yas--snippet-description-finish-runonce))
4385
4386 (defun yas--create-snippet-xrefs ()
4387 (save-excursion
4388 (goto-char (point-min))
4389 (while (search-forward-regexp "\\\\\\\\snippet[ \s\t]+`\\([^']+\\)'" nil t)
4390 (let ((template (get-text-property (match-beginning 1)
4391 'yasnippet)))
4392 (when template
4393 (help-xref-button 1 'help-snippet-def template)
4394 (kill-region (match-end 1) (match-end 0))
4395 (kill-region (match-beginning 0) (match-beginning 1)))))))
4396
4397 (defun yas--expand-uuid (mode-symbol uuid &optional start end expand-env)
4398 "Expand a snippet registered in MODE-SYMBOL's table with UUID.
4399
4400 Remaining args as in `yas-expand-snippet'."
4401 (let* ((table (gethash mode-symbol yas--tables))
4402 (yas--current-template (and table
4403 (gethash uuid (yas--table-uuidhash table)))))
4404 (when yas--current-template
4405 (yas-expand-snippet (yas--template-content yas--current-template)))))
4406 \f
4407 ;;; Utils
4408
4409 (defvar yas-verbosity 4
4410 "Log level for `yas--message' 4 means trace most anything, 0 means nothing.")
4411
4412 (defun yas--message (level message &rest args)
4413 "When LEVEL is above `yas-verbosity-level', log MESSAGE and ARGS."
4414 (when (> yas-verbosity level)
4415 (message "%s" (apply #'yas--format message args))))
4416
4417 (defun yas--format (format-control &rest format-args)
4418 (apply #'format (concat "[yas] " format-control) format-args))
4419
4420 \f
4421 ;;; Some hacks:
4422 ;;
4423 ;; The functions
4424 ;;
4425 ;; `locate-dominating-file'
4426 ;; `region-active-p'
4427 ;;
4428 ;; added for compatibility in emacsen < 23
4429 (unless (>= emacs-major-version 23)
4430 (unless (fboundp 'region-active-p)
4431 (defun region-active-p () (and transient-mark-mode mark-active)))
4432
4433 (unless (fboundp 'locate-dominating-file)
4434 (defvar locate-dominating-stop-dir-regexp
4435 "\\`\\(?:[\\/][\\/][^\\/]+[\\/]\\|/\\(?:net\\|afs\\|\\.\\.\\.\\)/\\)\\'"
4436 "Regexp of directory names which stop the search in `locate-dominating-file'.
4437 Any directory whose name matches this regexp will be treated like
4438 a kind of root directory by `locate-dominating-file' which will stop its search
4439 when it bumps into it.
4440 The default regexp prevents fruitless and time-consuming attempts to find
4441 special files in directories in which filenames are interpreted as hostnames,
4442 or mount points potentially requiring authentication as a different user.")
4443
4444 (defun locate-dominating-file (file name)
4445 "Look up the directory hierarchy from FILE for a file named NAME.
4446 Stop at the first parent directory containing a file NAME,
4447 and return the directory. Return nil if not found."
4448 ;; We used to use the above locate-dominating-files code, but the
4449 ;; directory-files call is very costly, so we're much better off doing
4450 ;; multiple calls using the code in here.
4451 ;;
4452 ;; Represent /home/luser/foo as ~/foo so that we don't try to look for
4453 ;; `name' in /home or in /.
4454 (setq file (abbreviate-file-name file))
4455 (let ((root nil)
4456 (prev-file file)
4457 ;; `user' is not initialized outside the loop because
4458 ;; `file' may not exist, so we may have to walk up part of the
4459 ;; hierarchy before we find the "initial UUID".
4460 (user nil)
4461 try)
4462 (while (not (or root
4463 (null file)
4464 ;; FIXME: Disabled this heuristic because it is sometimes
4465 ;; inappropriate.
4466 ;; As a heuristic, we stop looking up the hierarchy of
4467 ;; directories as soon as we find a directory belonging
4468 ;; to another user. This should save us from looking in
4469 ;; things like /net and /afs. This assumes that all the
4470 ;; files inside a project belong to the same user.
4471 ;; (let ((prev-user user))
4472 ;; (setq user (nth 2 (file-attributes file)))
4473 ;; (and prev-user (not (equal user prev-user))))
4474 (string-match locate-dominating-stop-dir-regexp file)))
4475 (setq try (file-exists-p (expand-file-name name file)))
4476 (cond (try (setq root file))
4477 ((equal file (setq prev-file file
4478 file (file-name-directory
4479 (directory-file-name file))))
4480 (setq file nil))))
4481 root))))
4482
4483 ;; `c-neutralize-syntax-in-CPP` sometimes fires "End of Buffer" error
4484 ;; (when it execute forward-char) and interrupt the after change
4485 ;; hook. Thus prevent the insert-behind hook of yasnippet to be
4486 ;; invoked. Here's a way to reproduce it:
4487
4488 ;; # open a *new* Emacs.
4489 ;; # load yasnippet.
4490 ;; # open a *new* .cpp file.
4491 ;; # input "inc" and press TAB to expand the snippet.
4492 ;; # select the `#include <...>` snippet.
4493 ;; # type inside `<>`
4494
4495 (defadvice c-neutralize-syntax-in-CPP
4496 (around yas--mp/c-neutralize-syntax-in-CPP activate)
4497 "Adviced `c-neutralize-syntax-in-CPP' to properly
4498 handle the end-of-buffer error fired in it by calling
4499 `forward-char' at the end of buffer."
4500 (condition-case err
4501 ad-do-it
4502 (error (message (error-message-string err)))))
4503
4504 ;; disable c-electric-* serial command in YAS fields
4505 (add-hook 'c-mode-common-hook
4506 '(lambda ()
4507 (dolist (k '(":" ">" ";" "<" "{" "}"))
4508 (define-key (symbol-value (make-local-variable 'yas-keymap))
4509 k 'self-insert-command))))
4510 \f
4511 ;;; Backward compatibility to yasnippet <= 0.7
4512
4513 (defvar yas--exported-syms '(;; `defcustom's
4514 ;;
4515 yas-snippet-dirs
4516 yas-prompt-functions
4517 yas-indent-line
4518 yas-also-auto-indent-first-line
4519 yas-snippet-revival
4520 yas-triggers-in-field
4521 yas-fallback-behavior
4522 yas-choose-keys-first
4523 yas-choose-tables-first
4524 yas-use-menu
4525 yas-trigger-symbol
4526 yas-wrap-around-region
4527 yas-good-grace
4528 yas-visit-from-menu
4529 yas-expand-only-for-last-commands
4530 yas-field-highlight-face
4531
4532 ;; these vars can be customized as well
4533 ;;
4534 yas-keymap
4535 yas-verbosity
4536 yas-extra-modes
4537 yas-key-syntaxes
4538 yas-after-exit-snippet-hook
4539 yas-before-expand-snippet-hook
4540 yas-buffer-local-condition
4541 yas-dont-activate
4542
4543 ;; prompting functions
4544 ;;
4545 yas-x-prompt
4546 yas-ido-prompt
4547 yas-no-prompt
4548 yas-completing-prompt
4549 yas-dropdown-prompt
4550
4551 ;; interactive functions
4552 ;;
4553 yas-expand
4554 yas-minor-mode
4555 yas-global-mode
4556 yas-direct-keymaps-reload
4557 yas-minor-mode-on
4558 yas-load-directory
4559 yas-reload-all
4560 yas-compile-directory
4561 yas-recompile-all
4562 yas-about
4563 yas-expand-from-trigger-key
4564 yas-expand-from-keymap
4565 yas-insert-snippet
4566 yas-visit-snippet-file
4567 yas-new-snippet
4568 yas-load-snippet-buffer
4569 yas-tryout-snippet
4570 yas-describe-tables
4571 yas-next-field-or-maybe-expand
4572 yas-next-field
4573 yas-prev-field
4574 yas-abort-snippet
4575 yas-exit-snippet
4576 yas-exit-all-snippets
4577 yas-skip-and-clear-or-delete-char
4578
4579 ;; symbols that I "exported" for use
4580 ;; in snippets and hookage
4581 ;;
4582 yas-expand-snippet
4583 yas-define-snippets
4584 yas-define-menu
4585 yas-snippet-beg
4586 yas-snippet-end
4587 yas-modified-p
4588 yas-moving-away-p
4589 yas-text
4590 yas-substr
4591 yas-choose-value
4592 yas-key-to-value
4593 yas-throw
4594 yas-verify-value
4595 yas-field-value
4596 yas-text
4597 yas-selected-text
4598 yas-default-from-field
4599 yas-inside-string
4600 yas-unimplemented
4601 yas-define-condition-cache
4602 yas-hippie-try-expand
4603 yas-active-keys
4604
4605 ;; debug definitions
4606 ;; yas-debug-snippet-vars
4607 ;; yas-exterminate-package
4608 ;; yas-debug-test
4609
4610 ;; testing definitions
4611 ;; yas-should-expand
4612 ;; yas-should-not-expand
4613 ;; yas-mock-insert
4614 ;; yas-make-file-or-dirs
4615 ;; yas-variables
4616 ;; yas-saving-variables
4617 ;; yas-call-with-snippet-dirs
4618 ;; yas-with-snippet-dirs
4619 )
4620 "Exported yasnippet symbols.
4621
4622 i.e. ones that I will try to keep in future yasnippet versions
4623 and ones that other elisp libraries can more or less safely rely
4624 upon.")
4625
4626 (defvar yas--dont-backport '(yas-active-keys)
4627 "Exported symbols that don't map back to \"yas/*\" variants.")
4628
4629 (dolist (sym (set-difference yas--exported-syms yas--dont-backport))
4630 (let ((backported (intern (replace-regexp-in-string "^yas-" "yas/" (symbol-name sym)))))
4631 (when (boundp sym)
4632 (make-obsolete-variable backported sym "yasnippet 0.8")
4633 (defvaralias backported sym))
4634 (when (fboundp sym)
4635 (make-obsolete backported sym "yasnippet 0.8")
4636 (defalias backported sym))))
4637
4638 \f
4639 (provide 'yasnippet)
4640
4641 ;;; yasnippet.el ends here
4642 ;; Local Variables:
4643 ;; coding: utf-8
4644 ;; byte-compile-warnings: (not cl-functions)
4645 ;; End: