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