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