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