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